Skip to content
Advertisement

How can I use the .findIndex() method be used in spliced arrays in Javascript?

I’ve been working throught the introduction to JavaScript course on Codecademy https://www.codecademy.com/courses/introduction-to-javascript/lessons/javascript-iterators/exercises/find-index and thought I would try to extend one of their ideas to search for all strings within an array that start with the string ‘s’.

I define an example array called animals and populate it with some strings. First I use the .findIndex() method to find the first animal name beginning with 's' and save its value to a variable named sIndex. Then I try to splice the animals array from sIndex + 1, apply findIndex() and then update sIndex with the value returned.

Here is the code I have so far:

JavaScript

However, when I run this in the console through node.js, I get the following error message:

JavaScript

I’m not sure what I’m doing that is causing the error? I would have thought my while loop should terminate due to the splicing.

Advertisement

Answer

So, basically yo have used slice (even though you said splice in question title). I would advice you to use the following code, it basically does the same thing, with a little less steps:

JavaScript
Advertisement