How to Sort Array of Objects in JavaScript

How to Sort Array of Objects in JavaScript

Ferenc Almasi β€’ 2020 August 10 β€’ Read time 2 min read
  • twitter
  • facebook
JavaScript

You can easily sort an array of objects in JavaScript based on the value of a given key with the following one-liner:

Copied to clipboard! Playground
// How to sort array of objects by value of key:
const comedians = [
    { name: 'Costello', dot: 1906 },
    { name: 'Abbott',   dot: 1897 }
];

comedians.sort((a, b) => a.name > b.name ? 1 : -1);

// Results in the following output:
[
    { name: 'Abbott',   dot: 1897 },
    { name: 'Costello', dot: 1906 }
];
sort.js

Based on this solution, you can also create a function to dynamically sort an array of objects, based on the passed key:

Copied to clipboard! Playground
const comedians = [
    { name: 'Costello', dot: 1906 },
    { name: 'Abbott',   dot: 1897 }
];

const sort = (array, key) => array.sort((a, b) => a[key] > b[key] ? 1 : -1);

sort(comedians, 'name') // Returns the same sorted array as in the previous example
sort.js

To further enhance this example, you can add the order as the third parameter:

Copied to clipboard! Playground
const sort = (array, key, order) => {
    const returnValue = order === 'desc' ? -1 : 1;

    return array.sort((a, b) => a[key] > b[key] ? returnValue * -1 : returnValue);
};

sort(comedians, 'name', 'desc');
sort(comedians, 'name', 'asc');
sort.js

Also, if you only need to sort simple data structures rather than objects, you can simply use sort:

Copied to clipboard!
[5, 4, 3, 2, 1, 0].sort(); // Will return [0, 1, 2, 3, 4, 5];
sort.js
How to Sort Array of Objects in JavaScript
If you would like to see more Webtips, follow @flowforfrank

Resource

  • twitter
  • facebook
JavaScript
Did you find this page helpful?
πŸ“š More Webtips
Mentoring

Rocket Launch Your Career

Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies:

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.