2

Here is how I tried creating a 2D array:

var data = new Array(10); // an array of length 10 all elements undefined

var twoDArray = data.map(function (d){
    return new Array(20);    // expected to be 2d array, but 10 elements all undefined
});

But now if I do the following I get results as expected:

var data = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
var twoDArray = data.map(function (d){
    return new Array(20);
});

2 Answers 2

2

That's because .map won't iterate over the values because they are all undefined.

You could use:

Array.apply(null, Array(10)).map(function() {
   return new Array(20);
});
Sign up to request clarification or add additional context in comments.

Comments

1

From MDN:

map calls a provided callback function once for each element in an array, in order, and constructs a new array from the results. callback is invoked only for indexes of the array which have assigned values; it is not invoked for indexes that are undefined, those which have been deleted or which have never been assigned values.

Thus you can't use map with an array full of undefined.

Comments

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.