Friday, November 23, 2018

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

Sort an array of objects in JavaScript

If you have an array of objects that you need to sort into a certain order, the temptation might be to reach for a JavaScript library. Before you do however, rember that you can do some pretty neat sorting with the native Array.sort function. In this article I'll show you how to sort an array of objects in JavaScript with no fuss or bother.

To follow along with this article, you will need a knowledge of basic JavaScript concepts, such as declaring variables, writing functions, and conditional statements. I'll also be using ES6 syntax. You can get a refresher on that here: https://www.sitepoint.com/tag/es6/

Basic Array Sorting

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

const foo = [9, 2, 3, 'random', 'panda'];
foo.sort(); // returns [ 2, 3, 9, 'panda', 'random' ]

const bar = [4, 19, 30, function(){}, {key: 'value'}];
bar.sort(); // returns [ 19, 30, 4, { key: 'value' }, [Function] ]

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

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

const baz = ['hello world', 31, 5, 9, 12];
baz.sort(); // baz array is modified
console.log(baz); // shows [12, 31, 5, 9, "hello world"]

To avoid this, you can create a new instance of the array to be sorted and modify that instead.

const baz = ['hello world', 31, 5, 9, 12];
const newBaz = baz.slice().sort(); // new instance of baz array is created and sorted
console.log(baz); // "hello world", 31, 5, 9, 12]
console.log(newBaz); // [12, 31, 5, 9, "hello world"]

Try it out

JS Bin on jsbin.com

Using Array.sort alone would not be very useful for sorting an array of objects, thankfully the function takes an optional compareFunction parameter which causes the array elements to be sorted according to the return value of the compare function.

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


by Olayinka Omole via SitePoint

No comments:

Post a Comment