Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript

H Yang
H Yang
2,066 Points

Spread operator, array.map, and initializing nested arrays

I want to create an array of arrays with initialized values, opting to use an array constructor. I'd like to get something that looks like

 [[false, false], [false, false], [false, false] ]

Can someone help me understand why my first attempt

  let truthTable = new Array(3);
  truthTable.map(() => {
    return new Array(2).fill(false);
  });

doesn't construct the array I want

but using the spread operator like so gets my desired result

  let truthTable = [... new Array(3)];
  truthTable.map(() => {
    return new Array(2).fill(false);
  });

This below seems to get the result I expect.

let arr2 = new Array(3).fill(new Array(2).fill(false) )

but it's an array of arrays which all point to the same array:

let arr2 = new Array(3).fill(new Array(2).fill(false) )
arr2[0][0] = true;
// arr2 = [ [true, false], [true, false], [true, false] ] 

What am I missing about the spread operator, map, constructing nested arrays?

1 Answer

Steven Parker
Steven Parker
215,939 Points

In your first example, the unfilled array is empty, so the map function doesn't find anything to work with. But instead of the spread operator, you could fill the array with a temporary value as you create it (let truthTable = new Array(3).fill(0);).

But map doesn't change the array directly, you still need to assign the result back to the original array.

Then your other issue is caused by the difference between map (which handles each element individually) and fill which will give each element a reference to the same object.

The most compact way to do what you want might be this:

let truthTable = Array(3).fill(false).map(x => Array(2).fill(x));
H Yang
H Yang
2,066 Points

Thank you for the explanation of how these things worked.