Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an empty copy of a 2D array in JavaScript?

I'm working on a project where I need to create an empty copy of a 2D array in JavaScript. I have an original array filled with the number of days in a month:

var originalArray = [
    [1, 2, 3, 4, 5, 6, 7], 
    [8, 9, 10, 11, 12, 13, 14], 
    [15, 16, 17, 18, 19, 20, 21], 
    [22, 23, 24, 25, 26, 27, 28], 
    [29, 30, 31]
];

Expected result:

copiedArray = [
    [, , , , , , ], 
    [, , , , , , ], 
    [, , , , , , ], 
    [, , , , , , ], 
    [, , ]
];

How do I create a new empty array with the exact number of elements as the original array? Thanks in advance!

I've tried a nested loop but not successful.

like image 517
William Avatar asked Oct 27 '25 04:10

William


1 Answers

something like this?

var originalArray = [
    [1, 2, 3, 4, 5, 6, 7], 
    [8, 9, 10, 11, 12, 13, 14], 
    [15, 16, 17, 18, 19, 20, 21], 
    [22, 23, 24, 25, 26, 27, 28], 
    [29, 30, 31]
];

const copiedArray = originalArray.map(a => Array(a.length).fill())

console.log(copiedArray)
like image 176
binga58 Avatar answered Oct 29 '25 19:10

binga58



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!