javascript - 如何用哈希值对这个数组进行排序?

标签 javascript arrays sorting

Possible Duplicate:
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 );

关于javascript - 如何用哈希值对这个数组进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11533445/

相关文章:

javascript - 带有按钮的面板不会出现在 trumbowyg 插件上

c# - 如何将二进制文件转换为字节数组?

java - 如何在不使用 ArrayList 的情况下在数组中添加两个单独的对象?

android - 无法从 XML 获取数组字符串资源

xml - 在golang中对降序结构进行排序

javascript - 转换表索引

JavaScript 无法处理更多加载的内容

javascript - Pinterest 如何保持图片高度成比例

javascript - 使用 SVG 在 CSS 中制作自定义图标

algorithm - 在一般情况下, `quicksort 3way` 会比 `quicksort` 慢吗?