FAQ: Arrays - More Array Methods

This community-built FAQ covers the “More Array Methods” exercise from the lesson “Arrays”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Web Development

Introduction To JavaScript

FAQs on the exercise More Array Methods

There are currently no frequently asked questions associated with this exercise – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this exercise. Ask or answer a question by clicking reply (reply) below.

If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this exercise, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head here.

Looking for motivation to keep learning? Join our wider discussions.

Learn more about how to use this guide.

Found a bug? Report it!

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

In number 3. of the exercises, it states:

“use .slice() to provide your friend with a list of these three things.”

corresponding to the array:

[‘orange juice’, ‘bananas’, ‘coffee beans’, ‘brown rice’, ‘pasta’, ‘coconut oil’, ‘plantains’].

Therefore, the correct answer should be: groceryList.slice(1, 2 ,3);
But in the solution it says: groceryList.slice(1, 4);

It doesn’t make any sense. It states listing three items: 'bananas' , 'coffee beans' , and 'brown rice' .

But according to the solution only two things should be listed.

This mistake made me click on "Solution " Which I don’t normally do.

9 Likes

array.slice(a, b) doesn’t work the way you’re thinking. It takes a ‘slice’ out of the array starting at index a and ending at but not including index b. In your example, bananas is at index 1, and brown rice is at index 3. groceryList.slice(1, 4) will return ['banana's, 'coffee beans', 'brown rice']. These are the elements at indexes 1, 2, 3. Might seem kinda quirky, but that’s how it works. Hope this helps!
Check out this link:

12 Likes

Wow, I guess I didn’t read through MDN well enough.

Now I get it :slight_smile:
Thanks

2 Likes

One certainly hopes you bookmarked that site. W3C pipes everything to them to disseminate for us. We can rely on this without the aid of outside sources mimicking as w3.org.

4 Likes

Why does it not include the final index number?

Good question. I don’t really know. It does allow for using slice() without a 2nd parameter:

myArray[1, 2, 3, 4, 5];
console.log(myArray.slice(3)); //3 is the starting index (inclusive)

Output:

[4, 5]

With only 1 parameter, slice() uses it as the starting index, and returns all elements from that point through the end of the array. If we only wanted the element at index 3:

myArray[1, 2, 3, 4, 5];
console.log(myArray.slice(3, 4)); //4 is now the 'up-to, but not including' index

Output:

[4]

Other than that, I don’t know.
Happy coding!

2 Likes

Hey @timmskiller, I was stuck with the same issue. I had to use a shell on my computer in order to understand the slice function. I think the problem comes in when when the MDN Documentation says to use the index. Based on the previous lesson we know the index on an array starts with 0, not one. But based on that I used the index 0 and not 1. It seems that for this function we need to use the 1 index as an entry and the last index past the one we would like to display. This is the code that I made

console.log("Creating an array named groceryList");

const groceryList = [‘orange juice’, ‘bananas’, ‘coffee beans’, ‘brown rice’, ‘pasta’, ‘coconut oil’, ‘plantains’];

console.log(“Now we are using the shift function”);
groceryList.shift();
console.log(groceryList);

console.log(“Now we are unshifting popcorn”)
groceryList.unshift(‘popcorn’);
console.log(groceryList);

console.log(“Now we are slicing the groceryList”);
console.log(groceryList.slice(1,4));

safe that to a file without the tags and then do: node filename.js

it should yield the same result. Maybe someone can correct me if I am wrong.

Thank you.

Why do almost all the array methods on MDN Web Docs have ‘prototype’ in them? And why doesn’t, for example, array.prototype.slice() work while array.slice() does in the codecademy editor?

2 Likes

Array.prototype.method() tells us that array objects inherit their methods from Array.prototype, not Array directly. Read up on the prototype object tied to each constructor in JS. It’s a bit more detailed than one can describe here.

Methods are invoked on the the array object, not on Array.prototype.

array.slice()
4 Likes
var array = [2, 9, 9];
console.log(array.indexOf(2));     // 0
console.log(array.indexOf(7));     // -1
console.log(array.indexOf(9, 2));  // 2
console.log(array.indexOf(2, -1)); // -1
console.log(array.indexOf(2, -3)); // 0

Hi, can anyone explain why console.log(array.indexOf(2, -1)) gives -1 but console.log(array.indexOf(2, -3)) gives 0 instead of -1? Thank you!

Index -3 is the same as index 0. The startfrom value is -3 so indexOf() starts at index 0, and finds 2 at that index.

Thanks mtf! But what’s the difference between the last 2 lines of codes?

console.log(array.indexOf(2, -1)); // -1
console.log(array.indexOf(2, -3)); // 0

Thank you!

1 Like

Recall that indexOf() always works from left to right regardless whether negative or positive indices used. By setting the startfrom index to -1, you are starting on the last element, and since it is not a 2, the return is -1 (not found).


Supplemental

Above we have found a method for determining if the last element is a given value.

array.indexOf(9, -1)    // <- 2

While not entirely practical, we could weave this into an algo that can count occurrences of a value in an array. More play possibilities if you have the time to go down that rabbit hole.

array.slice(-1) === 9    // <- true

Another index tool is the sister of indexOf() => lastIndexOf() which works the exact same way, and returns -1 for not found. It too can be fashioned to count occurrences, or at least locate the last occurrence of a given value.

1 Like

Thank you very much!

1 Like

I had an issue on step 5.

the exercise states:

" Call .indexOf() on groceryList to find the index of the element 'pasta' and save the returned value to a const variable named pastaIndex. Then log pastaIndex to the console"

The index/returned value is ‘4’ so I thought the answer would be:

const pastaIndex = 4
console.log(pastaIndex)

Instead the answer was:

const pastaIndex = groceryList.indexOf(‘pasta’)
console.log(pastaIndex)

Can someone elaborate for me?

2 Likes

Compare the given solution to the instructions. Which one follows the instructions to the letter, that one, or yours?

The instructions don’t ask us to literally set the variable, but to use a method on the array to determine the value, and assign the derived value. If we somehow shift the list around, your value will then be incorrect. The derived (dynamic) value will always be correct. That’s why we have such tools.

6 Likes

I was reading the MDN for half an hour trying to figure it out on my own, your comment helped me so much, thank you!

1 Like

Can you explain further this please? With another non-developer words. Thanks for your time!

pastaIndex = 4

The above is a literal assignment that assumes we know the index; i. e., have intimate beforehand knowledge of the contents and order of the array.

In a dynamic program with data streaming in or built from user inputs our program has no such intuition. This requires us to implement an Array method (array.indexOf()) so that we can supply any argument and if the term exists in the array, get its index.

1 Like