Languages
[Edit]
EN

JavaScript - sort array without mutating original one

0 points
Created by:
telsa
502

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' ]

 

See also

  1. JavaScript - sort array of integers

  2. JavaScript - sort array of objects

References

  1. Array.prototype.sort() - JavaScript | MDN
  2. Array.prototype.slice() - JavaScript | MDN
  3. Spread syntax (...) - JavaScript | MDN
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join