如何用哈希排序此数组? [英] How to sort this array with hashes?
本文介绍了如何用哈希排序此数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能重复:
如何对一组JavaScript对象进行排序?
Possible Duplicate:
How to sort an array of javascript objects?
我的输出看起来像这样:
I have output that looks like this:
[ { value: 1, count: 1 }, { value: 2, count: 2 } ]
我需要遍历数组中的哈希值,然后返回具有最高计数的值数字.看起来很简单,但我有些困惑.我尝试过使用单独的数组保存两组值,但是我不知道执行此操作的最佳方法.
I need to iterate through hashes in the array and then return the value number which has the highest count. Seems simple but I'm a bit stumped. I've tried using a separate array to save both sets of values but I can't figure out the best way to do it.
推荐答案
您可以执行以下操作:
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 );
这篇关于如何用哈希排序此数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文