1

I have listed several ways to create nested array and add value to sub array:

Way 1: works!

// Create empty nested array:    
var arrs = [[],[],[]];
arrs[0].push(1);
arrs[1].push(2);
arrs[2].push(3);

Then, not surprisingly, arrs is updated:

[[1],[2],[3]]

Way 2: works!

var arrs = [];
for (var i = 0; i < 3; i++) {
   arrs[i] = [];
 }

arrs[0].push(1);
arrs[1].push(2);
arrs[2].push(3);

arrs:

 [[1],[2],[3]]

Way 3: ?

var arrs = [];
var subArr = [];
for (var i = 0; i < 3; i++) {
   arrs[i] = subArr;
 }

arrs[0].push(1);
arrs[1].push(2);
arrs[2].push(3);

arrs:

[[1,2,3],[1,2,3],[1,2,3]]

My question: why the way 3 leads to arrs result as [[1,2,3],[1,2,3],[1,2,3]] rather than [[1],[2],[3]]?

3
  • 2
    it takes the same object reference. Commented Feb 3, 2018 at 21:29
  • Interesting observation, you are making changes to subArr thrice and the same changed object is referred by 3 objects in arr Commented Feb 3, 2018 at 21:33
  • Array.from({length: 3}, (_, i) => ([i + 1])); ... just saying Commented Feb 3, 2018 at 21:36

2 Answers 2

1

In your third way, you are assigning each element of arrs to the same array by reference: subArr. There is no copying, all three items in arrs point to the same value in memory.

Naturally, when you push to arrs[0], you are then pushing to subArr. Repeat 3 times, and you then have the result you are experiencing.

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

Comments

1

Because it's the same object!

If you did

arrs[i] = [];

You'd get a different result! You'd assign a new array each time instead of a reference to one array.

This is an easy trap to fall into in any programming language.

2 Comments

Exactly. I start my first programming language as Python (in which assignment pass the variable values instead of reference). I didn't realize that problem. Thanks.
Yeah, different languages do this in their own way. Python is a great language too, it's nice to play about with all these different ways of doing things, it's fun!

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.