Array Sorting

JavaScript includes two convenient methods for rearranging items inside an array, the sort() method and the reverse() method.

NOTE

These methods will alter the original array.

The sort() Method

The sort()open in new window method sorts the items of an array, affecting the original array, and returns the sorted array. The default sort order for the sort() method converts all items to strings and then compare their UTF-16 code unit values.

NOTE

By default, the sort() method will NOT always sort alphabetically, as uppercase and lowercase letters will have different UTF-16 values.

const primary = ['red', 'yellow', 'blue']
primary.sort() 
console.log(primary)// ['blue', 'red', 'yellow']

// Note the uppercase 'P' in 'Purple'
const secondary = ['orange', 'Purple', 'green']
secondary.sort()
console.log(secondary) // ['Purple', 'green', 'orange']

NOTE

By default, the sort() method will NOT sort numbers numerically, as all numbers will be converted to strings.

const numbers = [1, 20, 4, 100]

numbers.sort()

console.log(numbers) // [1, 100, 20, 4]

It is possible to alter the sort order of the sort() method by adding a compare function. This can make it possible to over the limitations of the default sort order.

const numbers = [1, 20, 4, 100]

// Adding a compare function to compare numbers
numbers.sort(function (a, b) {
  return a - b
})

console.log(numbers) // [1, 4, 20, 100]

The reverse() Method

The reverse() method reverses an array, affecting the original array, and returned the reversed array.

const colors = ['red', 'yellow', 'orange', 'purple', 'blue']
colors.reverse() 
console.log(colors)// ['blue', 'purple', 'orange', 'yellow', 'red']

In JavaScript, it is possible to chain methods together, like sort() and reverse() to get a "reverse alphabetically" order.

const colors = ['red', 'yellow', 'orange', 'purple', 'blue']
colors.sort().reverse() 
console.log(colors) // ['yellow', 'red', 'purple', 'orange', 'blue']

This YouTube video was created by Steve Griffith.