Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,851 questions

51,772 answers

573 users

How to clone a two-dimensional array in JavaScript

3 Answers

0 votes
let arr2D = [
    [1, 2, 3, 0],
    [4, 5, 6, 17],
    [7, 8, 9, 28]
];
 
let clonedArray = arr2D.map(innerArray => innerArray.slice());
 
console.log(clonedArray);
 
 
 
/*
run:
 
[ [ 1, 2, 3, 0 ], [ 4, 5, 6, 17 ], [ 7, 8, 9, 28 ] ]
 
*/

 



answered Mar 8, 2025 by avibootz
0 votes
let arr2D = [
    [1, 2, 3, 0],
    [4, 5, 6, 17],
    [7, 8, 9, 28]
];
 
let clonedArray = JSON.parse(JSON.stringify(arr2D));
 
console.log(clonedArray);
 
 
 
/*
run:
 
[ [ 1, 2, 3, 0 ], [ 4, 5, 6, 17 ], [ 7, 8, 9, 28 ] ]
 
*/

 



answered Mar 8, 2025 by avibootz
0 votes
let arr2D = [
    [1, 2, 3, 0],
    [4, 5, 6, 17],
    [7, 8, 9, 28]
];

let clonedArray = [];
let arr2D_length = arr2D.length;
for (let i = 0; i < arr2D_length; i++) {
    clonedArray[i] = [];
    let arr2D_i_length = arr2D[i].length;
    for (let j = 0; j < arr2D_i_length; j++) {
        clonedArray[i][j] = arr2D[i][j];
    }
}

console.log(clonedArray);



/*
run:

[ [ 1, 2, 3, 0 ], [ 4, 5, 6, 17 ], [ 7, 8, 9, 28 ] ]

*/

 



answered Mar 8, 2025 by avibootz

Related questions

1 answer 73 views
3 answers 89 views
1 answer 68 views
1 answer 76 views
1 answer 85 views
3 answers 103 views
3 answers 91 views
...