JavaScript

Find element index in array with JavaScript

October 23, 2021

Find element index in array with JavaScript

In this article, we will learn how to find element index in array, using a method that is already included in JavaScript and in a simple way.

find element index in array cover

What’s up, programmer, okay? Let’s learn one more new thing?

Watch this on YouTube:

One problem a JavaScript programmer will encounter in his career is finding the index of an element in an array

But to solve this issue, JavaScript already has a native function, making this task very simple

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?

To our delight, the JavaScript developers have also programmed a method for this.

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!

Conclusion

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! 

Want to learn more about best pratices in JavaScript? Click here!

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x