JavaScript Sorting Arrays
Sorting an Array
The sort() method sorts an array alphabetically:
const fruits = ["Banana", "Orange", "Apple", "Mango"];fruits.sort();
Reversing an Array
The reverse() method reverses the order of elements in an array:
const fruits = ["Banana", "Orange", "Apple", "Mango"];fruits.reverse();
By combining sort() and reverse(), you can sort an array in descending order:
const fruits = ["Banana", "Orange", "Apple", "Mango"];fruits.sort().reverse();
JavaScript Array toSorted() Method
ES2023 introduced the toSorted() method, which sorts an array without altering the original array.
const months = ["Jan", "Feb", "Mar", "Apr"];const sorted = months.toSorted();
JavaScript Array toReversed() Method
ES2023 introduced the toReversed() method, which reverses an array without altering the original array.
const months = ["Jan", "Feb", "Mar", "Apr"];const reversed = months.toReversed();
Numeric Sort
By default, the sort() function sorts values as strings, which may produce incorrect results for numbers. Use a compare function to sort numbers correctly:
const points = [40, 100, 1, 5, 25, 10];points.sort((a, b) => a - b); // Sorts in ascending order
To sort in descending order:
const points = [40, 100, 1, 5, 25, 10];points.sort((a, b) => b - a); // Sorts in descending order
The Compare Function
The compare function should return a negative, zero, or positive value to define the sort order:
const points = [40, 100, 1, 5, 25, 10];points.sort((a, b) => a - b); // Sorts in ascending order
Sorting an Array in Random Order
You can sort an array in random order using a compare function:
const points = [40, 100, 1, 5, 25, 10];points.sort(() => 0.5 - Math.random());
The Fisher-Yates Method
A more accurate method for random shuffling is the Fisher-Yates shuffle:
const points = [40, 100, 1, 5, 25, 10];for (let i = points.length - 1; i > 0; i--) { let j = Math.floor(Math.random() * (i + 1)); [points[i], points[j]] = [points[j], points[i]];}
Finding the Lowest (or Highest) Array Value
To find the lowest or highest value, you can sort the array and use the first or last element, or use Math.min() and Math.max().
Using Math.min() and Math.max()
const points = [40, 100, 1, 5, 25, 10];let min = Math.min(...points);let max = Math.max(...points);
Custom Min/Max Functions
For optimal performance, you can write custom functions to find the minimum or maximum values:
Find Min
function myArrayMin(arr) { let min = Infinity; for (let val of arr) { if (val < min) min = val; } return min;}
Find Max
function myArrayMax(arr) { let max = -Infinity; for (let val of arr) { if (val > max) max = val; } return max;}
Sorting Object Arrays
To sort arrays of objects, use a compare function that compares the desired property values:
Example: Sorting by Year
const cars = [ { type: "Volvo", year: 2016 }, { type: "Saab", year: 2001 }, { type: "BMW", year: 2010 }];cars.sort((a, b) => a.year - b.year);
Example: Sorting by Type (Alphabetically)
const cars = [ { type: "Volvo", year: 2016 }, { type: "Saab", year: 2001 }, { type: "BMW", year: 2010 }];cars.sort((a, b) => { let x = a.type.toLowerCase(); let y = b.type.toLowerCase(); return x < y ? -1 : x > y ? 1 : 0;});
Stable Array Sort
ES2019 revised the sort() method to ensure it uses a stable sorting algorithm, preserving the relative order of elements with equal values.
const myArr = [ { name: "X00", price: 100 }, { name: "X01", price: 100 }, { name: "X02", price: 100 }, { name: "X03", price: 100 }, { name: "X04", price: 110 }, { name: "X05", price: 110 }, { name: "X06", price: 110 }, { name: "X07", price: 110 }];myArr.sort((a, b) => a.price - b.price);