EN
JavaScript - copy two dimensional array
0
points
In this article, we would like to show you how to create a copy of a two-dimensional array in JavaScript.
1. Using slice() with map() method
In this example, we use slice() method inside map() to copy all elements from the original array.
// ONLINE-RUNNER:browser;
const array = [
['a', 'b'],
['c', 'd']
];
const copy = array.map((item) => item.slice());
console.log(JSON.stringify(copy)); // [ [ 'a', 'b' ], [ 'c', 'd' ] ]
2. Using slice() with for loop
In this example, we use slice() method inside a for loop to iterate through the array and copy all of its elements.
// ONLINE-RUNNER:browser;
var array = [
['a', 'b'],
['c', 'd']
];
var copy = [];
for (var i = 0; i < array.length; i++) {
copy[i] = array[i].slice();
}
console.log(JSON.stringify(copy)); // [ [ 'a', 'b' ], [ 'c', 'd' ] ]