Skip to content

How to sort arrays in JavaScript

In JavaScript, you can sort arrays using the sort() method. The sort() method sorts the elements of an array in place and returns the sorted array.

The sort() method sorts the elements of an array in ascending order by default. If you want to sort the elements in descending order, you can pass a compare function to the sort() method.

Sort Array of Numbers

const arr = [1, 2, 3, 4, 5];

// Sort in ascending order 
arr.sort((a, b) => a - b); // [1, 2, 3, 4, 5]

// Sort in descending order 
arr.sort((a, b) => b - a)); // [5, 4, 3, 2, 1]   

Sort Array of Strings

To sort an array of strings, you can use the localeCompare() method to compare strings.

const arr = ['Hi', 'Hola', 'Hello']; 

// Sort in ascending order 
arr.sort((a, b) => a.localeCompare(b)); // ['Hello', 'Hi', 'Hola'] 

// Sort in descending order 
arr.sort((a, b) => b.localeCompare(a)); // ['Hola', 'Hi', 'Hello']

Reverse Array

You can reverse the order of elements in an array using the reverse() method.

const arr = [1, 2, 3, 4, 5];

arr.reverse(); // [5, 4, 3, 2, 1]

Summary