Translate

Monday, 25 November 2019

Quick Tip: How to Sort an Array of Objects in JavaScript

If you have an array of objects that you need to sort into a certain order, you might be tempted to reach for a JavaScript library. But before you do, remember that you can do some pretty neat sorting with the native Array.sort function.

In this article, we'll show you how to sort an array of objects in JavaScript with no fuss or bother.

To follow along, you'll need a knowledge of basic JavaScript concepts, such as declaring variables, writing functions, and conditional statements. We'll also be using ES6 syntax. You can get a refresher on that via our extensive collection of ES6 guides. This popular article was updated in November 2019.

Sort an array of objects in JavaScript

Basic Array Sorting

By default, the JavaScript Array.sort function converts each element in the array that needs to be sorted into a string, and compares them in Unicode code point order.

const foo = [9, 1, 4, 'zebroid', 'afterdeck'];
foo.sort(); // returns [ 1, 4, 9, 'afterdeck', 'zebroid' ]

const bar = [5, 18, 32, new Set, { user: 'Eleanor Roosevelt' }];
bar.sort(); // returns [ 18, 32, 5, { user: 'Eleanor Roosevelt' }, Set {} ]

You may be wondering why 32 comes before 5. Not logical, huh? Well, actually it is. This happens because each element in the array is first converted to a string, and "32" comes before "5" in Unicode order.

It’s also worth noting that unlike many other JavaScript array functions, Array.sort actually changes, or mutates the array it sorts.

const baz = ['My cat ate my homework', 37, 9, 5, 17];
baz.sort(); // baz array is modified
console.log(baz); // shows [ 17, 37, 5, 9, 'My cat ate my homework' ]

To avoid this, you can create a new instance of the array to be sorted and modify that instead. This is possible using an array method that returns a copy of the array. For example, Array.slice:

const sortedBaz = baz.slice().sort(); // a new instance of the baz array is created and sorted

Or if you prefer a newer syntax, you can use the spread operator for the same effect:

const sortedBaz = [...baz].sort(); // a new instance of the baz array is created and sorted

The output is the same in both cases:

console.log(baz); // ['My cat ate my homework', 37, 9, 5, 17];
console.log(sortedBaz); // [ 17, 37, 5, 9, 'My cat ate my homework' ]

The post Quick Tip: How to Sort an Array of Objects in JavaScript appeared first on SitePoint.



No comments:

Post a Comment