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.
5
Answers
something like this?
maybe you can try this ?
if you want to make it recursive you can also do it like this :
The line above seems to do the job like you said. If you want to change the empty string to null or undefined, it will still work without any issues. You can run an example below to see whether it is upto your specs or not.
like this
You can use
Array.from
andfill()
like this: