我在通过浮点值对数组进行排序时遇到了一些麻烦。我在网上搜索过,并且我明白我必须使用比较功能,但我在理解这个概念时遇到了问题。通过浮点值对数组进行排序
我使用此代码来读取一个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