Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to sort an array

Short answer

For numbers, pass a comparison function to sort():

console.log([10, 9, 1].sort((a, b) => a - b).join(', '));

Output:

1, 9, 10

Descending order

Swap a and b:

console.log([10, 9, 1].sort((a, b) => b - a).join(', '));

Output:

10, 9, 1

Strings

localeCompare() compares strings using the rules of a language:

console.log(['apple', 'Pear', 'avocado'].sort((a, b) => a.localeCompare(b, 'en')).join(', '));

Output:

apple, avocado, Pear

By an object field

Access the property you need inside the comparison function:

const users = [
  { name: 'Anna', age: 30 },
  { name: 'Oleg', age: 25 },
];
users.sort((a, b) => a.age - b.age);
 
console.log(users.map((user) => user.name).join(', '));

Output:

Oleg, Anna

Keeping the original array

sort() modifies the array itself. To keep the original order, sort a copy:

const numbers = [3, 1, 2];
const sorted = [...numbers].sort((a, b) => a - b);
 
console.log(numbers.join(', '));
console.log(sorted.join(', '));

Output:

3, 1, 2
1, 2, 3

Common mistake

Without a comparison function, sort() compares numbers as strings:

console.log([10, 9, 1, 100].sort().join(', '));

Output:

1, 10, 100, 9

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.