EN
JavaScript - shallow copy multi-dimensional array
3
points
In this article, we would like to show you how to create a shallow copy of a multi-dimensional array in JavaScript.
Quick solution:
const copyArray = (value) => Array.isArray(value) ? value.map(copyArray) : value;
Practical example
In this example, array copy is realized recursively. The main idea is to check if the indicated value is Array type. If value is Array we do copy on the next level (dimension).
// ONLINE-RUNNER:browser;
const copyArray = (value) => Array.isArray(value) ? value.map(copyArray) : value;
// Usage example:
const array = [
[
['a', 'b'],
['c', 'd'],
],
[
['e', 'f'],
['g', 'h'],
]
];
const copy = copyArray(array);
console.log(JSON.stringify(copy)); // [[['a','b'],['c','d']],[['e','f'],['g','h']]]