Non-destructively reversing an array in Javascript

You can duplicate the array using ES6's spread operator, then destructively reverse the duplicate:

const arr1 = [1,2,3];
const arr2 = [...arr1].reverse();
// arr1 => [1,2,3]
// arr2 => [3,2,1]

You're making a shallow copy of the lines array. To copy the nested arrays, you need to slice each one.

var localLines = lines.map(function(arr) {
    return arr.slice();
});

The .map method will return a new Array of the return values, which are a slice of each nested Array.


FWIW, here's a shorter version that will work in modern browsers, though I'd probably stick with the first one.

var localLines = lines.map(Array.apply.bind(Array, null));

Tags:

Javascript