Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create new array without impacting values from old array

Tags:

javascript

I'm trying to create a copy of existing array and remove some items from array copy without impacting the original. I've tried this :

var new_arr = old_arr; //when I remove from new array the items from old array are also removed

How do I create entirely new copy of the existing array?

Update :

When I do this :

var new_arr = old_arr.slice();

then later :

new_arr[0].shift();
new_arr[1].shift();

The items from old_array get removed. This is a two dimensional array.

like image 610
London Avatar asked Jan 24 '13 10:01

London


People also ask

Which creates a new array out of the existing array?

from() The Array. from() method creates a new, shallow-copied Array instance from an array-like or iterable object.

Why does changing an array in JavaScript affect copies of the array?

An array in JavaScript is also an object and variables only hold a reference to an object, not the object itself. Thus both variables have a reference to the same object.


2 Answers

You can use two methods, this:

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

or this:

var newArray = oldArray.slice();
like image 182
sourcecode Avatar answered Sep 30 '22 11:09

sourcecode


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

like image 36
Bojoer Avatar answered Sep 30 '22 12:09

Bojoer