配列を浮動小数点値で並べ替えるのに問題があります。私はウェブ上で検索しましたが、私は比較関数を使用する必要があることを理解していますが、私はその概念を理解する問題を抱えています。配列を浮動小数点値で並べ替える
私はこのコードを使用して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"
SOLUTION
は(JSON.stringifyが判明です。問題の根源だった。これをconsole.logから削除します。その代わりに、console.log(hon)は正しいデータを表示し、正しくソートします。 Jsonはストリングを非常にうまく扱いません。
*だから、最高top2boxが最初でありますエントリ*それは 'b - a'でなければなりません。また、説明してください* top2boxのエントリが "1"に変更されました* – Rajesh
honを初期化しましたか?ああ、 – pokeybit
Honが初期化され、正しく表示されます。 @Rajesh出力のこのスクリーンショットを見てくださいhttp://imgur.com/a/s3Qvy Top2Box私はパーセント値を表示するはずです。 2番目のスクリーンショットは、維持したいがソートされた正しい値を示しています。 – n0rd