问题描述:

This question already has an answer here:

  • Sort ArrayList of custom Objects by property

    22 answers

网友答案:

You could use Array#sort.

var people = [{ firstname: 'Gosho', lastname: 'Petrov', age: 42 }, { firstname: 'Bay', lastname: 'Ivan', age: 81 }, { firstname: 'John', lastname: 'Doe', age: 42 }, { firstname: 'Pesho', lastname: 'Pesho', age: 22 }, { firstname: 'Asdf', lastname: 'Xyz', age: 81 }, { firstname: 'Gosho', lastname: 'Gosho', age: 22 }];

people.sort(function (a, b) {
    return a.age - b.age; // ascending
});

console.log(people);
.as-console-wrapper { max-height: 100% !important; top: 0; }
网友答案:

You can use Lodash sortBy() method.

https://lodash.com/docs#sortBy

var users = [
  { 'user': 'fred',   'age': 48 },
  { 'user': 'barney', 'age': 36 },
  { 'user': 'fred',   'age': 40 },
  { 'user': 'barney', 'age': 34 }
];

_.sortBy(users, [function(o) { return o.age; }]);

this will returns sorted new array

[['barney', 34], ['barney', 36], ['fred', 40], ['fred', 48]]
相关阅读:
Top