Topic Overview and Learning Goal

Welcome back, learners! Today, we will unravel the magic of JavaScript's built-in sort() function. We will discover how this excellent tool comes into play when managing extensive customer databases or arranging products in an online store. By mastering the sort() function, you can efficiently organize arrays in your code, ensuring a smoother user experience.

Introduction to JavaScript's sort function

Have you ever observed how products in an online shop are arranged? They're sorted in a specific order: alphabetically, by price, by popularity, etc. Similarly, in JavaScript, sorting helps to arrange arrays in a particular order.

Meet the hero of our lesson — the sort() function, a built-in method in JavaScript for sorting arrays. Let's examine how it works:

let friends = ["Tom", "Jerry", "Mickey", "Donald"];
friends.sort();

console.log(friends); 
// Output: ["Donald", "Jerry", "Mickey", "Tom"]
Sorting Numerical Arrays

Interestingly, sorting numbers in JavaScript is different. Let's unravel this:

let numbers = [5, 1, 8, 3];
numbers.sort();

console.log(numbers); // Output: [1, 3, 5, 8]

Everything works well until you sort an array like [15, 1, 100, 3]. You'll find that sort() treats numbers as strings! That's an unexpected result. Let's tackle this using a compare function (a, b) => a - b, which sorts numbers in ascending order. If the result of the provided compare function is negative, the 1st argument goes before the 2nd, and vice versa.

let numbers = [15, 1, 100, 3];
numbers.sort((a, b) => a - b); // This will sort numbers in ascending order

console.log(numbers); // Output: [1, 3, 15, 100]
Custom Sorting with JavaScript's Sort Function

The true power of sort() reveals itself when you provide a compare function. This function determines the sorting order. Let's look at an array of scores sorted in descending order:

let scores = [60, 90, 82, 100, 56];
scores.sort((a, b) => b - a);

console.log(scores); // Output: [100, 90, 82, 60, 56]

See? The compare function (a, b) => b - a helps sort the scores in descending order.

Multi-Factor Sorting in JavaScript
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal