我在通過浮點值對數組進行排序時遇到了一些麻煩。我在網上搜索過,並且我明白我必須使用比較功能,但我在理解這個概念時遇到了問題。通過浮點值對數組進行排序
我使用此代碼來讀取一個xlxs文件,並將我需要的值推送到一個更簡單的數組。我需要這樣的最高值是0的關鍵
這裏是我當前的代碼
// data is an array of arrays, lets loop through it to sort. The array contains each row of my xlxs file.
var hon = [] //array that will hold the sorted entries from the excel file
for(var i = 0; i < data.length; i++) {
// we dont want empty data. each row has a key named Business Unit. In empty rows the value of the key is the name of the key. We dont need that data.
if (data[i][3] != '' && data[i][0] != 'Business Unit') {
// data belongs to an actual person
// round top2box to display the percentage.
// push the values we need to a simpler array
hon.push({
country: data[i][0],
team: data[i][2],
name: data[i][3],
top2box: data[i][4],
sumofvotes: data[i][5]
})
}
}
// loop done lets sort each array entry by top2box value. So highest top2box is the first entry of the array
hon.sort(function(a,b) { return a.top2box - b.top2box;});
// show the result.
console.log(JSON.stringify(hon, null, 4));
但是顯示所有top2box條目已被更改的結果時,排序這個數組由top2box鍵的值到「1」並且沒有排序(很可能由於此)
hon的值是一個浮點數,需要稍後以百分比顯示。以下是一些示例值。我需要維護這些確切的值,但是爲了讓它們從最高到最低,所以我可以遍歷數組並稍後將它們顯示爲html。
"country": "Norway",
"team": "NO-Aftersales",
"name": "Andersen, Dennis",
"top2box": "0.47368421052631599",
"sumofvotes": "19"
這裏是另一個
"country": "Sweden",
"team": "SE-AS",
"name": "Vuong, Adele",
"top2box": "0.51515151515151503",
"sumofvotes": "33"
SOLUTION
原來JSON.stringify();是問題的根源。從console.log中刪除它。因此,它是console.log(hon)顯示正確的數據,並正確地排序它們。 Json stringify不漂浮很漂亮。
*所以最高top2box是第一入口*那麼它應該是'b - a'。另請解釋* top2box條目已更改爲「1」* – Rajesh
您是否初始化了hon? – pokeybit
哦對不起。 Hon初始化並正確顯示是。 @Rajesh看看輸出http://imgur.com/a/s3Qvy Top2Box的截圖,我應該顯示百分比值。第二個屏幕截圖顯示了我想維護但正確排序的正確值。 – n0rd