javascriptarrays

Reverse an array in JavaScript without mutating the original array


Array.prototype.reverse reverses the contents of an array in place (with mutation)...

Is there a similarly simple strategy for reversing an array without altering the contents of the original array (without mutation)?


Solution

  • You can use slice() to make a copy then reverse() it

    var newarray = array.slice().reverse();
    

    var array = ['a', 'b', 'c', 'd', 'e'];
    var newarray = array.slice().reverse();
    
    console.log('a', array);
    console.log('na', newarray);