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]
asked Apr 4, 2016 at 3:33
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]]);
answered Apr 4, 2016 at 3:35

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.