How To Sort An Array Without Mutating The Original Array In JavaScript?
Sorting arrays is a common task in JavaScript, especially when you need to present data in a specific order. However, maintaining the original array is often necessary especially if the original data will be required later in your code. In this article we'll see how we can sort an array in JavaScript while keeping the original array unmodified.
The sort() Method:
JavaScript provides a built-in sort() method to arrange the elements of an array. However, it's important to note that this method sorts the array in place, meaning it modifies the original array. This behavior might not be ideal, especially when working with immutable data or functional programming principles. To address this, you can create a copy of the array and sort that copy instead. Below are several methods to achieve this:
These are some approach to sort an array without mutating the original array :
1. Using the slice() Method
The method slice() returns a shallow copy of a section of an array into a new array object. You can create a copy that is sortable without changing the original array by applying slice() to the entire array.
Syntax
let sortedArray = array.slice().sort(compareFunction);
Example
const numbers = [4, 2, 5, 1, 3];
const sortedNumbers = numbers.slice().sort((a, b) => a - b);
console.log(numbers);
console.log(sortedNumbers);
Output
2. Using the Spread Operator (...)
This spread operator (...) can be used to make a shallow copy of an array. It provides a concise way to duplicate an array, allowing you to sort the copy without altering the original array.
Syntax
let sortedArray = [...array].sort(compareFunction);
Example
const names = ['Zoe', 'Alice', 'Bob'];
const sortedNames = [...names].sort();
console.log(names);
console.log(sortedNames);
Output
3. Using Array.from()
The Array.from() method can also be used to create a copy of an array. This method returns a new array instance from an array-like or iterable object, which you can then sort independently of the original array.
Syntax
let sortedArray = Array.from(array).sort(compareFunction);
Example
const letters = ['d', 'a', 'c', 'b'];
const sortedLetters = Array.from(letters).sort();
console.log(letters);
console.log(sortedLetters);