16

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.

London
  • 14,986
  • 35
  • 106
  • 147
  • 1
    Unlike an Array filled with simple values, your array is two-dimensional, i.e. it's filled with *object references*. Cloning it using `.slice()` will copy those references – but `new_arr[0]` will still refer to the same object as `old_arr[0]`. – fanaugen Jan 24 '13 at 10:51
  • 1
    Voting to reopen, because it's a duplicate of another question: http://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-clone-a-javascript-object – katspaugh Jan 24 '13 at 10:57
  • @fanaugen how do I make a copy of two dimensional array then? – London Jan 24 '13 at 11:20
  • 1
    @London see @sourcecode's answer below. With jQuery and `JSON.stringify` deep cloning is a snap. – fanaugen Jan 24 '13 at 13:13

6 Answers6

23

You can use two methods, this:

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

or this:

var newArray = oldArray.slice();
simhumileco
  • 31,877
  • 16
  • 137
  • 115
sourcecode
  • 1,802
  • 2
  • 15
  • 17
10

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

Bojoer
  • 898
  • 9
  • 19
2

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

Array.prototype.clone = function() { 
      return this.slice(0); 
}
Koste
  • 538
  • 6
  • 17
0

In Javascript, a two-dimensional array is just an array of arrays. Therefore, cloning one dimension is not enough. We also need to clone all the sub-dimension arrays. Here’s how we do it:

function cloneGrid(grid) {
  // Clone the 1st dimension (column)
  const newGrid = [...grid]
  // Clone each row
  newGrid.forEach((row, rowIndex) => newGrid[rowIndex] = [...row])
  return newGrid
}

// grid is a two-dimensional array
const grid = [[0,1],[1,2]]
newGrid = cloneGrid(grid)

console.log('The original grid', grid)
console.log('Clone of the grid', newGrid)
console.log('They refer to the same object?', grid === newGrid)
---
The original grid [ [ 0, 1 ], [ 1, 2 ] ]
Clone of the grid [ [ 0, 1 ], [ 1, 2 ] ]
They refer to the same object? false

Or if we take avantage of ES6 Array.map operation, we can make cloneGrid function even simpler:

const cloneGrid = (grid) => [...grid].map(row => [...row])

For more expanded answer read How to make a copy of an array in JavaScript

Sergey Stadnik
  • 3,100
  • 8
  • 27
  • 31
0

You can try .concat()

var old_arr = [1,2,3,4,5]
var new_arr = old_arr.concat()

console.log(old_arr) //1,2,3,4,5
console.log(new_arr) //1,2,3,4,5

new_arr.shift()

console.log(old_arr) //1,2,3,4,5
console.log(new_arr) //2,3,4,5
0

you may create a new array by using the spread operator. You can also find more about spread operator HERE.

cosnt oldArr = [{id: 1, name: 'Ali'}, {id:2, name: 'Raza'}];
cosnt newArray = [...oldArr];
console.log(newArray);
Ali Raza
  • 1,026
  • 13
  • 20