【问题标题】:How do I sort a group of objects based on an element of the objects? [duplicate]如何根据对象的元素对一组对象进行排序? [复制]
【发布时间】:2015-10-17 03:30:01
【问题描述】:

对象集合是

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

每个对象都包含许多元素

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

现在我想根据 valueIWantToSort 的值对对象进行排序。其中 valueIWantToSort 是一个数字。

【问题讨论】:

  • Array.prototype.sort...
  • 你的“组”是一个数组。您可以使用数组方法来完成这项工作。

标签: javascript angularjs coffeescript


【解决方案1】:

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

【讨论】:

猜你喜欢
  • 2021-12-09
  • 1970-01-01
  • 2013-11-25
  • 1970-01-01
  • 2012-08-01
  • 2021-03-24
  • 2014-05-29
  • 1970-01-01
  • 2015-06-17
相关资源
最近更新 更多