Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

2-dimensional arrays in ES6

Long story short, i'm looking for a way to create and fill 2D arrays using ES6, in an effort to avoid for loops. The created array should contain all 0s. I've tried many different approaches so i cant post all of them.

var [r, c] = [5, 5]; 
var m = Array(r).fill(Array(c).fill(0));

This works but it creates a bunch of instances of the same array, and adding slice Array(r).fill(Array(c).fill(0).slice()); doesn't help either.

I also tried creating the empty arrays and then looping trough them but that's a whole different problem, you apparently can't forEach() or map() an empty array, and i couldn't even loop through a filled one efficiently.

Am i missing something here? Are a whole lot of for loops the best way to approach this? It looks really messy and overly long. Any help appreciated.

like image 701
Mare_413 Avatar asked Dec 08 '22 15:12

Mare_413


2 Answers

Doing this worked for me:

var [r, c] = [5, 5]; 
var m = Array(r).fill().map(()=>Array(c).fill(0));

Basically just filling it with a dummy value so you can map over it

like image 191
vityavv Avatar answered Dec 11 '22 10:12

vityavv


You could use Array.from that takes a callback function and inside return arrays with 0's using fill method.

const arr = Array.from(Array(2), () => Array(5).fill(0))
console.log(arr)

Or you could just create array where each element is number of elements in sub-array and then use map and fill methods.

const arr = [5, 5].map(e => Array(e).fill(0))
console.log(arr)
like image 29
Nenad Vracar Avatar answered Dec 11 '22 11:12

Nenad Vracar