Sort
Lesson 14 of 18 in Coddy's Array Methods in JavaScript course.
The sort() method is a built-in function for arrays that helps you organize the elements in a specific order. By default, it sorts the elements alphabetically for strings or numerically for numbers. However, you can also customize the sorting behavior using a callback function to define your own sorting criteria.
Default Sorting: Imagine you have a list of movie titles (strings) and you want to sort them alphabetically (default sorting):
const movieTitles = ["The Shawshank Redemption", "The Godfather", "The Dark Knight", "Pulp Fiction"];
movieTitles.sort(); // Sorts in place
console.log(movieTitles); // Output: ["The Dark Knight", "The Godfather", "Pulp Fiction", "The Shawshank Redemption"]- In above example, we call
sort()onmovieTitles. - By default, it sorts the elements alphabetically based on their Unicode character codes.
console.log()displays themovieTitlesarray, which is now sorted alphabetically.
Custom Sorting for Numbers: Let's say you have an array of product ratings (numbers) and you want to sort them from highest to lowest:
const ratings = [4.5, 3.8, 5.0, 4.2];
ratings.sort((a, b) => b - a); // Custom comparison function for descending order
console.log(ratings); // Output: [5.0, 4.5, 4.2, 3.8]- In above example, we call
sort()onratings. - We provide a custom comparison function (
(a, b) => b - a) that subtracts the second element (b) from the first element (a). - If the result is positive (b is greater than a), elements are swapped (descending order).
Challenge
EasyYou're at the market, you have a list of prices (numbers) for various items that you want to buy, and these prices are given in the marketPrices array.
Your task is to write JavaScript code to sort the prices from least expensive to most expensive and log the updated array.
Try it yourself
const marketPrices = [10, 5, 20, 12, 8];
// Write code here