Javascript Array Sorting

November 01, 2021
  • The JavaScript Array sort() function sorts the elements in an array in place and returns the sorted array.
  • By default, the array elements are sorted alphabetically in ascending order(smallest-largest). To sort numerically or by a different order, we can pass in a comparing function.
  • The sort function is a mutating function which will modify the values of the original array.


Strings

Sorting alphabetically with mutation(bad practice)

const letters = ['a', 'c', 'b', 'd']
letters.sort()

console.log(letters)
> ["a", "b", "c", "d"]

We can sort without mutating the original array by using the slice() function. Slice will make a copy of the array before applying the sort

const letters = ['a', 'c', 'b', 'd']

console.log('sorted', letters.slice().sort())
console.log('original', letters)
> 
"sorted" ["a", "b", "c", "d"]
"original" ["a", "c", "b", "d"]

Same as above but using es6 syntax

const letters = ['a', 'c', 'b', 'd']

console.log('sorted', [...letters].sort())
console.log('original', letters)
> 
"sorted" ["a", "b", "c", "d"]
"original" ["a", "c", "b", "d"]

Now if we want to reverse the order, we can just add the reverse() function

const letters = ['a', 'c', 'b', 'd']

console.log([...letters].sort().reverse())
> ["d", "c", "b", "a"]

If we want to sort an array of mixed cases, then we need to write a custom comparer function

const letters = ['a', 'C', 'b', 'd']

console.log([...letters].sort())
> ["C", "a", "b", "d"] //not sorted properly

The comparer function takes two arguments a,b which is the two elements we’re comparing to each other. If the function returns a value >0 then the position of a and b is switched. if the value is <=0 then there is no change in the positions

function compare(a, b) {
    //temp variables as we don't want to change casing in the final output
    const x = a.toUpperCase()
    const y = b.toUpperCase()
    if (x < y ) {
        return -1;
    }
    if (y > x ) {
        return 1;
    }
    // values are equal
    return 0;
}

const letters = ['a', 'C', 'b', 'd']
const sortedLetters = [...letters].sort(compare)

console.log(sortedLetters)
> ["a", "b", "C", "d"]

Numbers

Lets checkout how to sort numbers. if we try to sort numbers without a comparer function, we’re going to have a bad time. The reason the elements are not sorted properly is because the sort converts the elements into strings and compares their sequences of UTF-16 code values

const numbers = [7, 6, 9, 10, 8];
numbers.sort()

console.log(numbers);
> [10, 6, 7, 8, 9] //not sorted properly

Comparer arrow function for ascending order sort. Note our comparer function from above can be simplified by using this short hand notation returning a-b.

const numbers = [7, 6, 9, 10, 8];
const newNumArray = [...numbers].sort((a,b) => {return a-b})

console.log(newNumArray)
> [6, 7, 8, 9, 10]

For a descending order we just return b-a

const numbers = [7, 6, 9, 10, 8];
const newNumArray = [...numbers].sort((a,b) => {return b-a})

console.log(newNumArray)
> [10, 9, 8, 7, 6]

Objects

Basic example of object sorting

const person = [
    {firstName: 'John', LastName: 'Doe'},
    {firstName: 'Bob', LastName: 'Ross'},
    {firstName: 'Luke ', LastName: 'Skywalker'},
];

const sortedPersonFirstName = person.slice().sort(function (x, y) {
    const a = x.firstName.toUpperCase();
    const b = y.firstName.toUpperCase();
    if (a > b)
      return 1
    if (a < b)
      return -1;
    return 0
});

console.log(sortedPersonFirstName)

[{
  firstName: "Bob",
  LastName: "Ross"
},{
  firstName: "John",
  LastName: "Doe"
},{
  firstName: "Luke",
  LastName: "Skywalker"
}]

© 2022, Built by Ron Pruitt using Gatsby