Create new array without impacting values from old array

You can use two methods, this:

function clone (src) {
    return JSON.parse(JSON.stringify(src));
}

or this:

var newArray = oldArray.slice();

A newer solution to do this is to use 'from' like this:

const newArr = Array.from(oldArr);

But this is a shallow copy and if nested elements are mutated they will project in the new created array with from. Best solution then would be to use

const newArr = JSON.parse(JSON.stringify(oldArr));

but also that method doesn't ensure all. If for example an element of the array contains a function like n => ++n then it will be null after using the JSON methods so best solution is deepClone and for that full explanation I refer to

Creating JavaScript Arrays


Using Yoshi answer you can extend Array prototype (just a simple helper):

Array.prototype.clone = function() { 
      return this.slice(0); 
}

Tags:

Javascript