可能重複:
How to sort an array of javascript objects?如何用哈希對這個數組進行排序?
我有輸出,看起來像這樣:
[ { value: 1, count: 1 }, { value: 2, count: 2 } ]
我需要遍歷數組中的哈希值進行迭代,然後返回值數其中計數最高。看起來很簡單,但我有點難住。我試過使用一個單獨的數組來保存兩組值,但我無法找出最好的方法來做到這一點。
可能重複:
How to sort an array of javascript objects?如何用哈希對這個數組進行排序?
我有輸出,看起來像這樣:
[ { value: 1, count: 1 }, { value: 2, count: 2 } ]
我需要遍歷數組中的哈希值進行迭代,然後返回值數其中計數最高。看起來很簡單,但我有點難住。我試過使用一個單獨的數組來保存兩組值,但我無法找出最好的方法來做到這一點。
你可以做這樣的事情:
var a = [{
value: 1,
count: 1
}, {
value: 2,
count: 2
}, {
value: 7,
count: 8
}, {
value: 5,
count: 0
}, {
value: 10,
count: 3
}];
// sorting using a custom sort function to sort the
// greatest counts to the start of the array
// take a look here: http://www.w3schools.com/jsref/jsref_sort.asp
// to understand how the custom sort function works
// better references can be found
// here: http://es5.github.com/#x15.4.4.11
// and here: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort
a.sort(function(v1, v2){
return v2.count - v1.count;
});
for (var i in a) {
console.log(a[i]);
}
// the greatest one is the first element of the array
var greatestCount = a[0];
console.log("Greatest count: " + greatestCount.count);
你da man,davidbuzatto – 2012-07-18 02:35:28
@ dsp_099,歡迎你! – davidbuzatto 2012-07-18 02:37:07
文檔:https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort(大多數人更喜歡MD3或MSDN到w3schools) – jbabey 2012-07-18 02:38:06
你確實需要的陣列來獲得最高的'count'元素進行排序?另外,這功課呢? – 2012-07-18 02:22:08
不,不是功課。你也是對的,我想排序並不是描述它的正確方法。我只需要對應最高計數的值 – 2012-07-18 02:22:54
問了一堆,JavaScript沒有散列。 ;) – epascarello 2012-07-18 02:24:22