Sorting object arrays by property values

How to sort an object array by a property values in JavaScript

Posted on July 9, 2020

So, we have an array of objects which we want to reorder – in this case by the orderIndex value.

const myArray = [
      id: 1,
      type: 'Cat',
      sound: 'Meow',
      orderIndex: 3
      id: 2,
      type: 'Dog',
      sound: 'Woof',
      orderIndex: 1
      id: 3,
      type: 'Cow',
      sound: 'Moo',
      orderIndex: 2
      id: 4,
      type: 'Sheep',
      sound: 'Baaaaa',
      orderIndex: 4

Arrays have a sort() method, Array.prototype.sort(), which we can use to sort arrays as shown below.
When 1 is returned, the function tells the sort() method that object b takes precedence in sorting over object a. Returning -1 does the opposite.

myArray.sort((a, b) => (a.orderIndex > b.orderIndex) ? 1 : -1);

The sort method can also be used on more simple, value arrays to order alphabetically or by numbers – The default sort order is ascending

const months = ['March', 'Jan', 'Feb', 'Dec'];


// output: Array ["Dec", "Feb", "Jan", "March"]