Hi there, I'm Marcos!

🗝️ Sorting an array of objects by a given key

const arr = [
  { name: 'James', age: 32 },
  { name: 'Lily', age: 33 },
  { name: 'Harry', age: 10 },
];

arr.sort((obj1, obj2) => obj1.age - obj2.age);

console.log(arr);
// [ { name: 'Harry', age: 10 },
//   { name: 'James', age: 32 },
//   { name: 'Lily', age: 33 } ]

This is how you can sort an array of objects by a given key. The sort method accepts a function that takes two parameters: the two items of the array that is going to be sorted, and must return a number. If the returned number is greater than 0 it means that the second item should go before the first one. If the returned number is less than 0 it means that the first item should go before the second one. If the returned number equals 0 it means that both items are the same in sorting terms.

Note that the sorting algorithm for arrays is executed in place, so the original array will be modified when using this method. If you don't want the original array to be changed you'll need to make first a copy.