Introduction

Plenty of times we need to sort elements of an array by a certain order. This becomes useful if we want to create say, order-by functionality on a web page for elements to be displayed.

The Array.prototype.sort() method

JavaScript offers a method for sorting an array. Syntax:

array.sort(compareFn?: (a: T, b: T) => Array<T>)

The compareFn is a callback function that is optional, an is supplied only when a comparison is needed in the sorting

const fruits = ['Mango', 'Banana', 'Apple', 'Peach']
fruits.sort()
console.log(fruits) // ['Apple', 'Banana', 'Mango']

For an array containing numbers:

const numbers = [21, 23, 43, 41, 15, 46, 57, 38, 19, 10]

console.log(numbers) // [10, 15, 19, 21, 23,38, 41, 43, 46, 57]

With compareFn callback.

Passing a compareFn callback function, we can pass in a function to compare each element and return a sorted array based on this.

Descending order(small to the largest in value):

const numbers = [21, 23, 43, 41, 15, 46, 57, 38, 19, 10]
numbers.sort((a, b) => {
  // sort elements in descending order
  return a - b
})

console.log(numbers) //

Ascending order(largest to smallest in value):

const numbers = [21, 23, 43, 41, 15, 46, 57, 38, 19, 10]
numbers.sort((a, b) => {
  // sort elements in ascending order
  return b - a
})
console.log(numbers) // [57, 46, 43, 41, 38, 23, 21, 19, 15, 10]

Summary

sort(cb(a, b) => {}) method sorts elements in place and accepts an optional callbakc function that can be used to define the “comparison” logic when sorting through each element.