简体   繁体   中英

JavaScript: Sort an array of objects by a numeric property in each object

I have a hard time understanding how to use the array.sort() method to sort an array of objects based on a numeric value found in every object. Essentially I have a scenario of the following form:

var myarray = []
myarray.push({name: "alex", age: 8})
myarray.push({name: "ben", age: 57})
myarray.push({name: "dan", age: 32})

The initial order of the result would be "alex, ben, dan". Now I want to sort this array by age, so the oldest people are first on the list. After sorting the order should be "ben, dan, alex". How do I achieve this in the simplest way possible?

You can use destructuring assignment and the .sort method like so:

 var myarray = [] myarray.push({name: "alex", age: 8}) myarray.push({name: "ben", age: 57}) myarray.push({name: "dan", age: 32}); var res = myarray.sort(({age:a}, {age:b}) => ba); console.log(res); 

Or, if you don't feel comfortable with destructing, you can use regular dot notation to access the age property:

 var myarray = [] myarray.push({name: "alex", age: 8}) myarray.push({name: "ben", age: 57}) myarray.push({name: "dan", age: 32}); var res = myarray.sort((a, b) => b.age-a.age); console.log(res); 

The way .sort works is defined by what you return from the callback function you pass in. If you return:

  • <= -1 then a will come before b .
  • 0 then keep a and b in the same positions
  • >= 1 then b will come before a

Thus, by calculating the difference between the two ages, this "naturally" gives the correct values to properly sort your array.

myarray.sort((a,b) => b.age - a.age)

Is the correct answer but nobody has helped with OP's question of having a hard time understanding sort. The function you pass into sort is the comparison function that when comparing two elements of the array should return less than 0 for a comes first, 0 if they are equal and greater than 0 for b comes first.

I use this default comparer function in my projects

defaultCompare = (a, b) => (!a && !b ? 0 : !a ? -1 : !b ? 1 : a < b ? -1 : a > b ? 1 : 0);

as undefined, null, NaN and other falsey values can throw a spanner in there on you.

ES6

myarray.sort((a,b) => b.age - a.age)

ES5

myarray.sort(function(a,b){return b.age - a.age})

Detailed description of the sort function can be found here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

*Edited to sort in descending order as OP asked

Thanks everyone. I solved it by using this option:

data.sort(function(a, b) { return b.score - a.score })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM