0

Why is the map() not being invoked here?

let N = 16;
let fullSizeBufs = Array(2).map((x) =>
  Array(N).fill(-1)
)
console.log(fullSizeBufs)

We get

[undefined, undefined]

I even put a breakpoint on the Array(N).fill(-1) : it is not hit. The map() is just skipped. What is the correct syntax for this?

Phil
  • 157,677
  • 23
  • 242
  • 245
WestCoastProjects
  • 58,982
  • 91
  • 316
  • 560
  • Thanks @Phil for putting in the `code snippet`: I'll try to pick up that little skill! – WestCoastProjects Jun 03 '20 at 03:39
  • You might be interested in `Array.from({ length: N }, () => -1)` as well – Phil Jun 03 '20 at 03:42
  • @Phil yes - that's more directly expressing the intent – WestCoastProjects Jun 03 '20 at 03:43
  • Does this answer your question? [JavaScript "new Array(n)" and "Array.prototype.map" weirdness](https://stackoverflow.com/questions/5501581/javascript-new-arrayn-and-array-prototype-map-weirdness) and [Most efficient way to create a zero filled JavaScript array?](https://stackoverflow.com/questions/1295584/most-efficient-way-to-create-a-zero-filled-javascript-array) Seriously everything on SO is so hard to find nowadays – user120242 Jun 03 '20 at 04:11

2 Answers2

3

You have to fill the first array, or map has nothing to iterate on. The Array constructor initializes with references undefined, which is not the same as [undefined, undefined, undefined], which is actually an array of 3 references to undefined.
eg: [,,,].map(x=>console.log(x)) vs [undefined,undefined,undefined].map(x=>console.log(x))

let N = 16;
let fullSizeBufs = Array(2).fill(0).map((x) =>
  Array(N).fill(-1)
)
console.log(fullSizeBufs)
user120242
  • 14,918
  • 3
  • 38
  • 52
2

You could use a spread operator with the first array to make it iterable.

let N = 16;
let fullSizeBufs = [...Array(2)].map((x) =>
  Array(N).fill(-1)
)
console.log(fullSizeBufs)
WestCoastProjects
  • 58,982
  • 91
  • 316
  • 560