What’s up, programmer, okay? Let’s learn one more new thing?
Watch this on YouTube:
For this specific problem, let’s use the indexOf method, and insert a parameter that is the element we need to find
So let’s go to the example:
let numeros = [0, 1, 2, 1, 0]; console.log(numeros.indexOf(1)); // 1
Here we will receive 1 as an answer, which is the return of the function
And the first index we find element 1 in the array numbers, cool right?
So we’ve already solved our problem 🙂
What if we wanted the last index?
We can now use the lastIndexOf, which will return the last index of the element we send as a parameter.
See it running:
let numeros = [0, 1, 2, 1, 0]; console.log(numeros.lastIndexOf(1)); // 3
In this case it returns index 3, as it is the last index where element 1 is found!
In this article we learned a way to find the index of an element within an array and also the last index of an element in an array
For this we use the indexOf and lastIndexOf methods
And that’s it for today, see you on the next post!