A Few Minutes Of Code
A Few Minutes Of Code

    How to sort an array of objects in javascript

    June 14, 2019

    Video Blogger

    image from undraw.co

    To sort an array of objects in javascript we need to pass the key we want to sort by into the sort Array.

    We can use our learnings from our article about sorting items numerically to sort an array of objects.

    Take the below example

    const myArray = [
      { id: 111, name: 'John', age: 29 },
      { id: 112, name: 'Sarah', age: 25 },
      { id: 122, name: 'Kate', age: 22 },
      { id: 123, name: 'Tom', age: 21 },
      { id: 125, name: 'Emma', age: 24 },
    ];

    To sort by age smallest to largest, pass in the age key.

    console.log(
      myArray
      .sort((a,b) => a.age - b.age)
      .map(item => item.age) // just mapping age for smallest result
      )
    // outputs [21, 22, 24, 25, 29]

    There is also another syntax which you might come across which can be a bit cleaner and reusable.

    const highestToLowest = key => (a, b) => b[key] - a[key]
    const lowestToHighest = key => (a, b) => a[key] - b[key]

    This will allow us to pass in our function directly into the sort.

    eg

    console.log(
      myArray
      .sort(lowestToHighest('age'))
      .map(item => item.age) // just mapping age for smallest result
      )
      // outputs [21, 22, 24, 25, 29]
    
    console.log(
      myArray
      .sort(highestToLowest('age'))
      .map(item => item.age) // just mapping age for smallest result
      )
      // outputs [29, 25, 24, 22, 21]

    I find this the best solution because we are able to test this function and reuse it with confidence across our codebase, also by giving a descriptive name to the function we help prevent getting our ascending and descending orders mixed up.

    Categories:
    Previous How to sort an array alphabetically in javascriptNext How to sort by multiple items in javascript