0

I don't know why isnt this snippet working:

Array(50).map(e => { e = {id: Math.random() , content: 'some_content'}; return e });
4
  • Use Array.from({length: 50}) as Array.from({length: 50}).map(e => ({id: Math.random() , content: 'some_content'}));. Commented Feb 8, 2017 at 10:11
  • nice make it an answer so i can accept it Commented Feb 8, 2017 at 10:12
  • What is "undefined x 1" in JavaScript? Commented Feb 8, 2017 at 10:12
  • 2
    Uninitialized array entries are skipped over by map, foreach etc. You can use spread syntax to create an iterable of n elements [...Array(50)].map() Commented Feb 8, 2017 at 10:16

3 Answers 3

1

It of course does what you told it to do, just not what you want it to do.

The problem is that the map function "is invoked only for indexes of the array which have assigned values, including undefined." Calling Array(50) creates 50 empty slots, but does not assign to them, so the map does nothing.

As someone else suggested, you can use Array.from() to quickly create an array of 50 elements, assigned to undefined.

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

3 Comments

@MattEllen -- there is a difference between an unassigned element and an element assigned to undefined. So far as I know, the only way to test that difference directly is with hasOwnProperty(), but this problem demonstrates the issue indirectly.
It's also an issue between Firebug and Firefox's consoles. Firefox says "[ <10 empty slots>, 40 more... ]" whereas Firebug shows me an array of 50 undefineds. I guess it's time to ditch Firebug :D
It's also akin to a sparse array, e.g. let x = [1,2]; x[7] = 3;. Entires 2...6 will be unassigned and skipped by map.
1

You could use Array.apply and wrap the mapped return value in parenthesis, to return an object.

var array = Array.apply(null, { length: 50 }).map(_ => ({id: Math.random() , content: 'some_content'}));
console.log(array)

2 Comments

we are talking about 50 elements here. i see no performance problem ...
yes, I know ... depends if someone wants 50, or 5000000 random numbers :p (oh, and it's not SLOW, that was my bad :p )
0

var result = Array.apply(null, { length: 50 }).map(e => { e = {id: Math.random() , content: 'some_content'}; return e });
console.log(result);

or

  var result = [...Array(50)].map(e => { e = {id: Math.random() , content: 'some_content'}; return e });
    console.log(result);

1 Comment

Array.apply(null, { length: 50 }) wont work for lengths > 500000 (in firefox)

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.