【发布时间】:2017-12-19 09:23:58
【问题描述】:
我在按浮点值对数组进行排序时遇到了一些问题。我在网上搜索过,我知道我必须使用比较功能,但我在理解这个概念时遇到了问题。
我正在使用此代码读取 xlxs 文件并将所需的值推送到更简单的数组。我需要按 top2box 键的值对这个数组进行排序,所以最大值是键 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 条目都已更改为“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"
解决方案
原来是 JSON.stringify();是问题的根源。从 console.log 中删除它。因此,它改为 console.log(hon) 显示正确的数据并正确排序。 Json stringify 对浮点数的处理不是很好。
【问题讨论】:
-
所以最高的 top2box 是第一个条目那么它应该是
b - a。另请说明top2box 条目已更改为“1” -
你初始化了吗?
-
对不起。 Hon 已初始化并正确显示 yes。 @Rajesh 看看这个输出的屏幕截图imgur.com/a/s3Qvy Top2Box 我应该显示百分比值。第二个屏幕截图显示了我想要维护但已排序的正确值。
-
从您的屏幕截图看来,
top2box是一个字符串,您必须先解析它,然后再在sort中进行比较。尝试parseFloat(a.top2box) - parseFloat(b.top2box),您还可以使用排序值更新hon,hon = hon.sort()。 -
@n0rd 问题不是由您共享的任何代码引起的。请查看您的完整代码,了解值的更新位置
标签: javascript arrays node.js sorting