Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Sorting arrays

Sorting puts elements in order: products by price, names alphabetically, tasks by deadline. In JavaScript the sort() method does this. You can give it a comparison rule, and then it will sort anything.

sort for strings

Without arguments, sort() puts strings in alphabetical order:

const names = ['Oleg', 'Anna', 'Ira'];
 
names.sort();
 
console.log(names.join(', ')); // Anna, Ira, Oleg

sort() changes the array itself and returns that same array.

The compare function

To set your own order, pass a compare function to sort(). It receives two elements a and b and returns a number: negative means a goes first, positive means it goes after, zero means the order does not matter. For numbers, subtracting one from the other is enough:

const prices = [300, 25, 1000, 7];
 
prices.sort((a, b) => a - b);
 
console.log(prices.join(', ')); // 7, 25, 300, 1000

Descending order

To get the reverse order, just swap a and b:

const prices = [300, 25, 1000, 7];
 
prices.sort((a, b) => b - a);
 
console.log(prices.join(', ')); // 1000, 300, 25, 7

The reverse() method simply flips the array back to front without comparing anything.

Strings by language rules

Plain string comparison is case-sensitive: capital letters come before lowercase ones. The localeCompare() method compares strings the way the language does, and it fits a compare function:

const words = ['pear', 'Apple', 'banana'];
 
words.sort((a, b) => a.localeCompare(b));
 
console.log(words.join(', ')); // Apple, banana, pear

An array of objects

Objects are sorted by one of their properties — the compare function reads it from a and b:

const products = [
  { title: 'Coffee', price: 12 },
  { title: 'Tea', price: 5 },
  { title: 'Juice', price: 8 },
];
 
products.sort((a, b) => a.price - b.price);
 
console.log(products.map((p) => p.title).join(', ')); // Tea, Juice, Coffee

Common mistake

Without a compare function, sort() compares elements as strings, even when they are numbers. The string '10' starts with '1', so it comes before '9':

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

Also remember that sort() changes the original array. If you still need it in the old order, use toSorted() — it takes the same compare function but returns a sorted copy:

const prices = [300, 25, 1000];
const sorted = prices.toSorted((a, b) => a - b);
 
console.log(sorted.join(', ')); // 25, 300, 1000
console.log(prices.join(', ')); // 300, 25, 1000

Thanks for reading!

Donate to the site — we work hard for you.