Languages
[Edit]
EN

JavaScript - shallow copy multi-dimensional array

3 points
Created by:
Giles-Whittaker
739

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']]]

 

See also

  1. JavaScript - copy two dimensional array

References

  1. Array.isArray() - JavaScript | MDN
  2. Array.prototype.map() - JavaScript | MDN

Alternative titles

  1. JavaScript - create copy of multi-dimensional array
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join