代码之家  ›  专栏  ›  技术社区  ›  dsp_099

如何使用哈希对数组进行排序?[副本]

  •  0
  • dsp_099  · 技术社区  · 13 年前

    可能重复:
    How to sort an array of javascript objects?

    我的输出如下所示:

    [ { value: 1, count: 1 }, { value: 2, count: 2 } ]
    

    我需要迭代数组中的散列,然后返回计数最高的数值。看起来很简单,但我有点不知所措。我曾尝试使用一个单独的数组来保存这两组值,但我无法找到最好的方法。

    1 回复  |  直到 8 年前
        1
  •  2
  •   davidbuzatto    13 年前

    你可以这样做:

    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 );