6

Riddle me this.

Let's say you new up an array of 1,000 elements and want to assign the index of each element as the element's value using .map(). I would expect it to work like so:

new Array(1000).map((element, i) => i);

Here's the problem: the new array returned, while having the required 1,000 elements, is empty, despite assigning the .map()'s return value to be the array index. This can be remedied by chaining .fill(0) like so:

new Array(1000).fill(0).map((element, i) => i);

But why?

Why do .map or .filter require a populated array to produce a populated array?

user229044
  • 232,980
  • 40
  • 330
  • 338
  • Jared Smith, any chance of getting the article with the accepted answer retitled with something a little more descriptive of the contents of the question? I think my title's a little more search friendly than "weiredness." –  Nov 15 '17 at 21:52
  • What do you want it to be? – lilezek Nov 15 '17 at 21:55
  • You're welcome to lift my title wholesale. I had a bummer of a time searching for the answer on this (hence the question). –  Nov 15 '17 at 21:55

2 Answers2

4

To make it working you can use the spread operator in ECMA6

console.log([...new Array(1000)].map((element, i) => i))
loretoparisi
  • 15,724
  • 11
  • 102
  • 146
2

It is mainly because the array must be filled, even with undefined pointers in order to be iterated. With new Array() it is not.

From MDC (emphasis mine): "map calls a provided callback function once for each element in an array, in order, and constructs a new array from the results. The callback is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values."

According to the first comment of the accepted answer of this thread:

JavaScript "new Array(n)" and "Array.prototype.map" weirdness

lilezek
  • 6,976
  • 1
  • 27
  • 45