17

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.

4
  • 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]. Commented Jan 24, 2013 at 10:51
  • 1
    Voting to reopen, because it's a duplicate of another question: stackoverflow.com/questions/122102/… Commented Jan 24, 2013 at 10:57
  • @fanaugen how do I make a copy of two dimensional array then? Commented Jan 24, 2013 at 11:20
  • 1
    @London see @sourcecode's answer below. With jQuery and JSON.stringify deep cloning is a snap. Commented Jan 24, 2013 at 13:13

6 Answers 6

25

You can use two methods, this:

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

or this:

var newArray = oldArray.slice();
Sign up to request clarification or add additional context in comments.

3 Comments

Why would you need jQuery for the first solution?
I like the method with JSON, it is so simple and beautiful !
The JSON method may be simple, but it is veery sloooow, and it will fail completely if your array contains circular elements - e.g. JSX...so need to be very careful with that one!
12

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

Comments

2

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

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

6 Comments

It doesn't help here, as the OP needs a deep clone.
Yes you are correct, but London later updated his question that array is two dimensional.
Two-dimensianal, yes, that's exactly why your solution won't help.
Yes, that's why my splice won't help. I posted this answer before London updated his question.
Oh, I see. You need to either edit your answer according to the updated question or remove it completely.
|
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

Comments

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

Comments

-1

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);

1 Comment

Spread operator will only work if the array contains primitive data types, in your example the newArray still points to the old objects inside the array

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.