Skip to main content

Sorting Arrays in JavaScript

By SamK
0
0 recommends
Category(s)
Topic(s)

In this tutorial, you'll learn about various ways to sort arrays in JavaScript.

Sorting an Array

The sort() method in JavaScript arranges elements in an array in alphabetical order.

Example:

const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
console.log(fruits);
// Output: ["Apple", "Banana", "Mango", "Orange"]

Reversing an Array

The reverse() method rearranges elements in the array in opposite order.

Example:

const colors = ["Red", "Blue", "Green", "Yellow"];
colors.reverse();
console.log(colors);
// Output: ["Yellow", "Green", "Blue", "Red"]

Sorting in Descending Order

By using both sort() and reverse(), an array can be sorted in descending order.

Example:

const animals = ["Dog", "Cat", "Elephant", "Zebra"];
animals.sort().reverse();
console.log(animals);
// Output: ["Zebra", "Elephant", "Dog", "Cat"]

Sorting Without Modifying the Original Array

JavaScript toSorted()

Introduced in ES2023, the toSorted() method creates a new sorted array without altering the original one.

Example:

const days = ["Monday", "Tuesday", "Wednesday", "Thursday"];
const sortedDays = days.toSorted();
console.log(sortedDays);
console.log(days); // Original array remains unchanged

// Output:
["Monday", "Thursday", "Tuesday", "Wednesday"]
["Monday", "Tuesday", "Wednesday", "Thursday"]

JavaScript toReversed()

Similar to toSorted(), toReversed() creates a new reversed array while keeping the original array intact.

Example:

const shades = ["Light", "Dark", "Medium"];
const reversedShades = shades.toReversed();
console.log(reversedShades);
console.log(shades); // Original array remains unchanged

// Output:
["Medium", "Dark", "Light"]
["Light", "Dark", "Medium"]

Shuffling an Array Randomly

Using sort() with Random Function

const values = [80, 200, 10, 15, 50, 30];
values.sort(() => 0.5 - Math.random());
console.log(values);
// Output: Array(6) [ 80, 200, 10, 15, 30, 50 ]

Finding Minimum and Maximum Values

JavaScript lacks built-in methods for finding the highest or lowest array values. Here are three approaches:

  • Sorting to Find Min/Max
const values = [80, 200, 10, 15, 50, 30];
values.sort((x, y) => x - y);
console.log("Min:", values[0], "Max:", values[values.length - 1]);
// Output: Min: 10 Max: 200
  • Using Math.min() and Math.max()
const nums = [80, 200, 10, 15, 50, 30];
console.log("Min:", Math.min(...nums));
console.log("Max:", Math.max(...nums));
// Output: 
Min: 10
Max: 200
  • Custom Function to Find Min/Max
function findMin(arr) {
 return arr.reduce((min, num) => (num < min ? num : min), arr[0]);
}

function findMax(arr) {
 return arr.reduce((max, num) => (num > max ? num : max), arr[0]);
}

const numbers = [80, 200, 10, 15, 50, 30];
console.log("Min:", findMin(numbers));
console.log("Max:", findMax(numbers));
// Output: 
Min: 10
Max: 200

Sorting Objects in JavaScript

Sorting objects requires comparing property values.

Sorting by Numeric Property

const cars = [
 { model: "Toyota", year: 2016 },
 { model: "Volvo", year: 2001 },
 { model: "BMW", year: 2010 }
];
cars.sort((a, b) => a.year - b.year);
console.log(cars);

// Output: 
[
  { model: "Volvo", year: 2001 },
  { model: "BMW", year: 2010 },
  { model: "Toyota", year: 2016 }
]

Sorting by String Property

const cars = [
    { model: "Toyota", year: 2022 },
    { model: "Honda", year: 2021 },
    { model: "BMW", year: 2023 }
];

cars.sort((a, b) => a.model.localeCompare(b.model));

console.log(cars);

// Output: 
[
  { model: "BMW", year: 2023 },
  { model: "Honda", year: 2021 },
  { model: "Toyota", year: 2022 }
]

Questions & Answers