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 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:

The instructions state:
Push [“dog”, 3] onto the end of the myArray variable.

I don’t know how you can say they did not tell you what to push.

To expand on what [“dog”, 3] represents, it is just an array itself. So, you are pushing one array into another array. After the push statement, myArray looks like

[["John", 23], ["cat", 2], ["dog", 3]]

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”); ?

That would depend if you were being asked to push [“dog”] or push “dog”. The former is an array with one string element. The latter is just a string.

FYI - Arrays can have no elements (an empty array), one element, or multiple elements.

1 Like

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']).


Ok gotcha thanks alot