如何根据对象的元素对一组对象进行排序?

时间:2015-10-16 18:54:42

标签: javascript angularjs coffeescript

对象集合是

[Object, Object, Object, Object, Object, Object, Object, Object, Object]

每个对象都有许多元素

{value1: someValue, valueIWantToSort: someNumericValue, value2: someValue, value3: someValue,...}

现在我想根据valueIWantToSort的值将对象按顺序放置。其中valueIWantToSort是一个数字。

1 个答案:

答案 0 :(得分:-2)

首先要阅读documentation

TL; DR:我们使用传递给数组的本机排序函数的比较器函数!

//[Object, Object, Object, Object, Object, Object, Object, Object, Object];
    /*
    {
        value1: someValue, 
        valueIWantToSort: someNumericValue, 
        value2: someValue, 
        value3: someValue,
    ...}
    */

var myArray=[];
var i=0;
for(i;i<10;i++){
  myArray.push({
        value1: 'someValue', 
        valueIWantToSort: Math.round(Math.random() *100 ) ,
        value2: 'someValue', 
        value3: 'someValue',
  });
};
document.body.innerHTML += "Before sorting :<br> " + JSON.stringify( myArray ) + "<hr>";

myArray.sort( function(a,b){ return  a.valueIWantToSort > b.valueIWantToSort })


document.body.innerHTML += "After sorting :<br> " + JSON.stringify( myArray ) + "<hr>";

myArray.sort( function(a,b){ return  a.valueIWantToSort < b.valueIWantToSort })
// here we invert the sort order -----------------------^

document.body.innerHTML += "After sorting inverted:<br> " + JSON.stringify( myArray );