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.
In this example, we use slice()
method inside map()
to copy all elements from the original array
.
xxxxxxxxxx
1
const array = [
2
['a', 'b'],
3
['c', 'd']
4
];
5
6
const copy = array.map((item) => item.slice());
7
8
console.log(JSON.stringify(copy)); // [ [ 'a', 'b' ], [ 'c', 'd' ] ]
In this example, we use slice()
method inside a for loop to iterate through the array and copy all of its elements.
xxxxxxxxxx
1
var array = [
2
['a', 'b'],
3
['c', 'd']
4
];
5
6
var copy = [];
7
8
for (var i = 0; i < array.length; i++) {
9
copy[i] = array[i].slice();
10
}
11
12
console.log(JSON.stringify(copy)); // [ [ 'a', 'b' ], [ 'c', 'd' ] ]