Sort an array in JS - how to guide! Javascript and typescript

October 26, 2018

It is very simple to sort in Javascript.

The methods on this page also apply to typescript.

Just use the .sort() method. But there are a few important things to know and be aware of:

Sorting a-z, just use .sort().

One important thing to know about sorting in Javascript/Typescript is that it sorts in place You probably won't always want to mutate the original array.

For that reason, in all the examples below it spreads the array (to make a copy - with [...originalArray]) so the original is not touched.

word_array = [
    "animal",
    "phone",
    "water",
    "computer",
    "bottle",
];
console.log([...word_array].sort()); 
    // (5) ["animal", "bottle", "computer", "phone", "water"]

Sorting arrays of numbers in Javascript/Typescript

However, if you use .sort() on an array of numbers it will not sort it correctly:

        num_array = [
            1000,
            200,
            22,
            2,
            102,
            199,
            150,
            100000,
            2.24,
        ];
        console.log([...num_array].sort()); //(9) [1000, 100000, 102, 150, 199, 2, 2.24, 200, 22]

The output from this - [1000, 100000, 102, 150, 199, 2, 2.24, 200, 22] is clearly not sorted properly.

It sorted it by comparing character by character, as if it was a string comparison.

You can fix this by providing a comparison function to sort, like this:

        num_array = [
            1000,
            200,
            22,
            2,
            102,
            199,
            150,
            100000,
            2.24,
        ];
        console.log([...num_array].sort(function(a,b) { return a-b; }));

And this will now output the correctly sorted array: [2, 2.24, 22, 102, 150, 199, 200, 1000, 100000]

How to sort arrays of objects in Javascript/Typescript

You can easily sort arrays of object in Javascript, by giving your own custom function. It is similar to how sorting by numbers (previous example) in Javascript/Typescript works.

Let's say you have an array of objects in Javascript, with this shape:

const people = [
    { name: "Pete", age: 50 },
    { name: "Sam", age: 40 },
    { name: "Pat", age: 20 },
];

To sort these objects by age (numeric sort):

const sortedPeople = [...people].sort((a, b) => a.age - b.age);

To sort these by the name key, you can do it like this:

const sortedPeople = [...people].sort((a, b) => a.name - b.name);

How to avoid mutating the original array due to sorting in place

const array1 = ['a', 'z', 'b'];
const array2 = array1.sort();
console.log(array1 === array2); // true! they're the same object

// spread the array to avoid mutating original array
const array3 = ['d', 'x', 'a'];
const array4 = [...array3].sort()
console.log(array3 === array4); // false! array3 is untouched