EN
JavaScript - sort array without mutating original one
0
points
In this article, we would like to show you how to sort an array without mutating the original one in JavaScript.
1. Using slice() method
In this example, we use slice() method to create a copy of array. Then we sort the copy using sort() method.
// ONLINE-RUNNER:browser;
const array = ['a', 'c', 'b'];
const sorted = array.slice().sort();
console.log(array); // [ 'a', 'c', 'b' ]
console.log(sorted); // [ 'a', 'b', 'c' ]
2. Using spread operator (ES6)
In this example, we use the spread operator (...) to create a copy of array. Then we sort the copy using sort() method.
// ONLINE-RUNNER:browser;
const array = ['a', 'c', 'b'];
const sorted = [...array].sort();
console.log(array); // [ 'a', 'c', 'b' ]
console.log(sorted); // [ 'a', 'b', 'c' ]