0

I need to add some arrays to another array.

Suppose I have 2 nested loops:

arr1 = [];

for (i = 0; i < 3; i++) {
  for (j = 0; j < 3; j++) {
    arr1.push(i,j)
  }
}

I want arr1 to be

[[[0],[0]],[[0],[1]],[[0],[2]],[[1],[0]],...]

Instead I just get

[0, 0, 0, 1, 0, 2, 1, 0, 1, 1, 1, 2, 2, 0, 2, 1, 2, 2]
2
  • [[0][0]] is not valid Javascript. Do you mean [0, 0] or [[0], [0]]? Commented Apr 4, 2016 at 3:36
  • @szym: I corrected that. Commented Apr 4, 2016 at 3:37

1 Answer 1

8

Array.push appends each argument to the array, so this is expected behavior. To accomplish what you want you should call

arr1.push([[i], [j]]);
Sign up to request clarification or add additional context in comments.

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.