How to sort array of objects by 2 property values – JavaScript

Here's how to order an array of objects by multiple property values.

I want to order my friends:

  • First the oldest.
  • If they have the same age, first the tallest.

We'll use Array.prototype.sort()

const friends = [ { name: 'Friend 1', age: 30, height: 1.8 }, { name: 'Friend 2', age: 17, height: 1.85 }, { name: 'Friend 3', age: 18, height: 1.75 }, { name: 'Friend 4', age: 25, height: 2 }, { name: 'Friend 5', age: 25, height: 1.8 } ]
friends.sort((a, b) => { let n = b.age - a.age; if (n !== 0) return n; return b.height - a.height; });

Result

As you can see the friend 4 and 5, who have the same age have been sorted by tallest first.

[[object Object] { age: 30, height: 1.8, name: "Friend 1" }, [object Object] { age: 25, height: 2, name: "Friend 4" }, [object Object] { age: 25, height: 1.8, name: "Friend 5" }, [object Object] { age: 18, height: 1.75, name: "Friend 3" }, [object Object] { age: 17, height: 1.85, name: "Friend 2" }]

Leave a Reply

Add <code> Some Code </code> by using this tags.

*
*