2017-07-14 58 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

相關問題