Home > Mobile >  Javascript: pushing an array into an array
Javascript: pushing an array into an array

Time:02-06

JS question: I need to push an array to be an element in another array. I got 2 ways: a plain push() and one the same but with spread operator

arr.push([newArr]);
 arr.push([...newArr]);

(both arr and newArr are arrays)

What does the spread operator actually accomplishes here? Observing in the console, in the 2nd example, I get the results I want:

res[0] (3) [1, 2, 3]

So the array I pushed becomes an element in the new array. so far so good.

But in the 1st example, without the spread operator, I get:

res[0] [Array(3)]

res[0][0] (3) [1, 2, 3]

And this is what I don't understand. why, when not using spread, I get what seems to be like... sort of a wrapper... over the array? what does it even mean, when I get [Array(x)] in the console?? is it array within array or...?

so the question is: what is this [Array(x)], why is is there, and why does the spread operator clears it out?

Thank You!

CodePudding user response:

Let's take a look at this example

const newArr = [1,2,3];

const a1 = [newArr];
const a2 = [...newArr];

console.log(a1);
console.log(a2);

In the first case, newArr becomes the first element of the array a1. In the second case, spread operator takes all the elements of the newArr and put them one by one as elements of the array a2. So a1==[newArr], a2==[newArr[0], newArr[1], newArr[2]]

CodePudding user response:

Consider your array arr as a row of lockers.

When you use arr.push([newArr]); you're taking that entire array [newArr], and putting the entire thing into the next available locker. If newArr contains 3 values (lockers) of its own, all three go into that next, single available locker in arr as newArr, expanding the arr array to accommodate the site, in this case adding 1 locker.

When you use the spread operator, arr.push([...newArr]);, you're taking each of the elements of newArr out of newArr, and putting each one in turn into the next available locker in the row. If newArr has 3 values (lockers) of its own, the first goes into the next available locker in arr, the 2nd into the 2nd available locker in arr, and the 3rd into the 3rd, expanding the arr array to accommodate the site, in this case adding 3 lockers.

The spread operator essentially flattens the array, whereas push does not.

CodePudding user response:

arr.push([newArr]); pushes an array with one item newArr into arr. arr.push([...newArr]); pushes a shallow copy of newArr into arr.

Spread syntax.

  • Related