Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Vic Mercier
Vic Mercier
3,276 Points

Two dimensional array

Can we add something at a specific place in a two dimensional array with for loops.(using the push méthode?)

2 Answers

Steven Parker
Steven Parker
229,732 Points

The push method only adds to the end.

When you use push, you don't specify the place, the new items always go on the end of the array.

Push method, no. As Steven indicated, push only adds items to the end of an array, but you can add content using the splice method (with a for loop if you feel like it...)

let fruit = ["banana", "orange", "apple"];
const animal = "cat";
let num = 0;

for(item in fruit){
    fruit.splice(num, 0, animal);
    num = num + 2;
};
console.log(fruit);

Output:

[ 'cat', 'banana', 'cat', 'orange', 'cat', 'apple' ]

The first parameter in the splice method specifies where in the array (fruit) you would like to add your content. I indicated here I would like to use my variable num, but this can be a static number. The second parameter specifies how many items to remove from the array, which I indicated here as 0. If there is an item already in the fruit[num] position, it will be pushed to the next position within the array. The third parameter is what content would you like to place inside the array (fruit) at our fruit[num] position.

I chose a dynamic variable to demonstrate when you might want to use a for loop, but if you are looking to place something at a specific location within an array, it would be best to do it like so

let fruit = ["banana", "orange", "apple"];
fruit.splice(2, 0, "cat"); //cat in position 2 of the fruit array