Reputation: 15274
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.
Upvotes: 16
Views: 43524
Reputation: 1073
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);
Upvotes: -1
Reputation: 107
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
Upvotes: 0
Reputation: 3218
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
Upvotes: 0
Reputation: 948
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
Upvotes: 12
Reputation: 1802
You can use two methods, this:
function clone (src) {
return JSON.parse(JSON.stringify(src));
}
or this:
var newArray = oldArray.slice();
Upvotes: 24
Reputation: 538
Using Yoshi answer you can extend Array prototype (just a simple helper):
Array.prototype.clone = function() {
return this.slice(0);
}
Upvotes: 2