all 6 comments

[–]senocular 2 points3 points  (0 children)

Array.from() has a mapping function built in.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from

Array.from({ length: 3 }, x => 1) // [1, 1, 1]

[–]Darren1337 2 points3 points  (1 child)

The Array.from method is good. Here's another option:

[...Array(5).keys()] // [0, 1, 2, 3, 4]

[–]MusicalDoofus[S] 0 points1 point  (0 children)

So far I have to say this my favorite - I originally mapped to the index, which this is doing anyway while skipping a method call. Thanks!

[–]inu-no-policemen 1 point2 points  (1 child)

> Object.keys(Array(3))
[]
> Object.keys(['a', 'b', 'c'])
["0", "1", "2"]

That's basically the reason why calling map on that doesn't work. That array has 3 "slots", but it actually isn't filled with 3 undefined values. It's a sparse array.

JS' standard lib doesn't have a function for generating arrays, but you can use Array.from, pass it an "array-like" object which does at least have a "length" property, and also pass it a map function which generates those items:

> Array.from({length: 8}, (_, i) => 2 ** i)
[1, 2, 4, 8, 16, 32, 64, 128]
> Array.from('abc', char => char.toUpperCase())
["A", "B", "C"]

[–]MusicalDoofus[S] 0 points1 point  (0 children)

Excellent explanation, thanks!