How to Sort Array Elements in JavaScript

Contents
In this article, you will learn how to sort array elements in JavaScript.
Sorting array elements in JavaScript
In JavaScript, you can use several methods to sort array elements. Here are some methods you can use:
Using the Array.prototype.sort() method
This method sorts the elements of an array in place and returns the sorted array. By default, the method sorts elements in lexicographic (alphabetical) order. However, you can specify a custom sorting function to sort elements in a different order.
Example
const arr = [3, 1, 4, 2, 5];
arr.sort(); // Sort elements in lexicographic order
console.log(arr); // Output: [1, 2, 3, 4, 5]
const arr2 = [3, 1, 4, 2, 5];
arr2.sort((a, b) => b - a); // Sort elements in descending order
console.log(arr2); // Output: [5, 4, 3, 2, 1]
Using the Array.prototype.reverse() method
This method reverses the order of the elements in an array in place and returns the reversed array.
Example
const arr = [1, 2, 3, 4, 5];
arr.reverse();
console.log(arr); // Output: [5, 4, 3, 2, 1]
Using the spread operator
This operator allows you to create a new array with the same elements as an existing array. You can use this operator to sort elements in a new array without modifying the original array.
Example
const arr = [3, 1, 4, 2, 5];
const sortedArr = [...arr].sort();
console.log(sortedArr); // Output: [1, 2, 3, 4, 5]
console.log(arr); // Output: [3, 1, 4, 2, 5]
Using the Array.from() method
This method creates a new array from an array-like object or an iterable object. You can use this method to sort elements in a new array without modifying the original array.
Example
const arr = [3, 1, 4, 2, 5];
const sortedArr = Array.from(arr).sort();
console.log(sortedArr); // Output: [1, 2, 3, 4, 5]
console.log(arr); // Output: [3, 1, 4, 2, 5]