Affiliate link

CSS Tutorial - Semantic UI

Learn how to sort array and objects with different methods.

Sorting Array

JavaScript Array sort() method

sort() method can be used to sort an array.

By default, sort() method is used to sort string and it will automatically casts array elements to string.

const numbersArray = [0, 1, 8, 5, 50, 10, 80];
numbers.sort();
console.log(numbers);

Code result

0, 1, 10, 5, 50, 8, 80

As you notice, sort() orders 10 before 2 because string "10" is before string "2" when comparing first alphabet.

To use sort() method for ordering numbers, we have to pass in a compare function as an argument for sort() method.

JavaScript Array sort() method - with compare function

Advertisment
Fiverr
Get Surfshark VPN