对象集合是
[Object, Object, Object, Object, Object, Object, Object, Object, Object]
每个对象都有许多元素
{value1: someValue, valueIWantToSort: someNumericValue, value2: someValue, value3: someValue,...}
现在我想根据valueIWantToSort的值将对象按顺序放置。其中valueIWantToSort是一个数字。
答案 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 );