In my quest to avoid using traditional for
loops, I am searching for a method to generate and populate 2D arrays using ES6. The goal is to have an array filled with all 0s. While I've attempted various strategies, the following code demonstrates one approach:
var [r, c] = [5, 5];
var m = Array(r).fill(Array(c).fill(0));
Although this code works, it results in multiple instances of the same array being created. Even attempting to use slice()
doesn't resolve this issue:
Array(r).fill(Array(c).fill(0).slice());
.
Another strategy involved creating empty arrays and then iterating through them. However, I encountered a new challenge - you cannot use forEach()
or map()
on an empty array, and looping efficiently through a populated array proved to be problematic.
Am I overlooking something here? Are numerous for loops truly the most effective solution? This approach seems convoluted and unnecessarily lengthy. Any assistance would be greatly appreciated.