Languages
[Edit]
EN

JavaScript - reverse array without mutating original array

0 points
Created by:
Adnaan-Robin
724

In this article, we would like to show you how to reverse an array without mutating the original array in JavaScript.

Quick solution:

// ONLINE-RUNNER:browser;

var array = ['a', 'b', 'c'];
var arrayCopy = array.slice().reverse();

console.log(arrayCopy); // [ 'c', 'b', 'a' ]

Explanation:

In the example above the slice() method returns a shallow copy of the array. The reverse() method reverses the copy of the array and saves the result in arrayCopy.

 

See also

  1. JavaScript - reverse array

References

  1. Array.prototype.slice() - JavaScript | MDN
  2. Array.prototype.reverse() - JavaScript | MDN

Alternative titles

  1. JavaScript - reverse array without mutating original one
  2. JavaScript - reverse array without changing original array
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