Manipulate Arrays With push()

Tell us what’s happening:
myArray.push(“dog”, 3); I wrote this code with confidence and then when I got it wrong I tried and tried to get it right and after 15-30min I gave up and checked on the internet.

And then the right answer was this: myArray.push([“dog”, 3]); Makes no sense in the example there are no [] and on devoloper.mozilla.org they don’t use ([x)] either do w3schools.

Can someone please explain why my answer is wrong and the other right?

Your code so far
myArray.push(“dog”, 3);


// Example
var ourArray = ["Stimpson", "J", "cat"];
ourArray.push(["happy", "joy"]); 
// ourArray now equals ["Stimpson", "J", "cat", ["happy", "joy"]]

// Setup
var myArray = [["John", 23], ["cat", 2]];

// Only change code below this line.
myArray.push(["dog", 3]);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/manipulate-arrays-with-push

The argument for push is whatever new element you want to add to the array. In the case of this challenge, the new element is itself an array. If we look at the example…

// ourArray now equals ["Stimpson", "J", "cat", ["happy", "joy"]]

See how the last element of ourArray is ["happy", "joy"]? That means that a new array of two strings was added. That array is a single element of the larger array.

Now let’s look at myArray

var myArray = [["John", 23], ["cat", 2]];

myArray is an array containing two elements. Each element is an array. (This is called a multi-dimensional array.) The goal of the challenge is to add a third element to myArray. That element is the array ["dog", 3].

I understand now that im pushing an array because there are two values didn’t think about that. So let’s say there was only dog and not the 3. Would the correct answer then be myArray.push(“dog”); ?

It depends on what you want myArray to be when you’re done. If the last element should be string, then myArray.push('dog') if it should be an array then myArray.push(['dog']).

2 Likes

Ok gotcha thanks alot