2017-07-14 151 views
1

我在通过浮点值对数组进行排序时遇到了一些麻烦。我在网上搜索过,并且我明白我必须使用比较功能,但我在理解这个概念时遇到了问题。通过浮点值对数组进行排序

我使用此代码来读取一个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不漂浮很漂亮。

+1

*所以最高top2box是第一入口*那么它应该是'b - a'。另请解释* top2box条目已更改为“1”* – Rajesh

+0

您是否初始化了hon? – pokeybit

+0

哦对不起。 Hon初始化并正确显示是。 @Rajesh看看输出http://imgur.com/a/s3Qvy Top2Box的截图,我应该显示百分比值。第二个屏幕截图显示了我想维护但正确排序的正确值。 – n0rd

回答

1

您需要保存这样的“排序”的结果:

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); 

你可以阅读更多有关排序在这里 - Array#Sort和大约这里箭功能 - Functions#ArrowFunctions

+0

感谢您的回复!我尝试了这一点,但它将top2box的所有值更改为1。 '{ “国”: “丹麦”, “团队”: “DK-售后服务”, “名”: “Skaaning,拉斯穆斯”, “top2box”: “1”, “sumofvotes”:“ 4" }, { “国”: “瑞典”, “团队”: “”, “名”: “Rosenius,尼克拉斯”, “top2box”: “1”, “sumofvotes”: “1” }' 原来它们是浮点值。例如:0.241232我需要保持这一点,但按照从高到低的顺序排列。 – n0rd

+0

'排序'不能更改道具的类型或值。 要按照从高到低的顺序对它们进行排序,您需要使用'b - a'。 – fauster01

+0

'(a,b)=> {return a.top2box - b.top2box}'是一种矫枉过正(*至少对我来说)。你可以直接做'(a,b)=> a.top2box - b.top2box' – Rajesh

相关问题