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?

4

2 Answers 2

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)

Sign up to request clarification or add additional context in comments.

2 Comments

ah ya - I'm still a bit color blind wrt javascript
This is probably the most direct answer but I like the spread operator approach as well
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)

2 Comments

I like this better than Array(2).fill(0)
ES6 is the gift that keeps on giving.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.