按浮点值sorting数组

我有一些麻烦sorting一个浮点值的数组。 我search了networking,我知道我必须使用比较函数,但是我有理解这个概念的问题。

我正在使用这个代码来读取一个xlxs文件,并将我需要的值推到一个更简单的数组。 我需要通过top2box键的值sorting这个数组,所以最高的值是键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”并且没有sorting(由于这个原因也是可能的)

洪的价值是一个浮动,这将需要以百分比后显示。 以下是一些示例值。 我需要维护这些确切的值,但是从高到低sorting,所以我可以遍历数组,然后显示为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)显示正确的数据,并正确地sorting它们。 Json stringify不漂浮很漂亮。

你需要像这样保存“sorting”的结果:

 var hon = [ { country: 'some country', team: 'some team', name: 'some name', top2box: 123123, sumofvotes: 123123 }, { country: 'some country2', team: 'some team2', name: 'some name2', top2box: 123, sumofvotes: 123 } ]; hon = hon.sort((a, b) => {return a.top2box - b.top2box}); // save the sort result // (a - b) = Ascending sort, (b - a) = Descending sort console.log(hon); 

你可以在这里阅读更多关于sorting – 数组#sorting和关于箭头函数 – 函数#ArrowFunctions