Last updated on Oct 31, 2021 by Suraj Sharma
In this tutorial, you’ll learn how you can get the index of an item in an array in JavaScript using array’s built-in methods.
The indexOf
method returns the index of the first matched item from a given array. However, it returns -1
if the item is not present in the array.
const vehicles = ['Cars', 'Buses', 'Trains', 'Airplanes'];
vehicles.indexOf('Bikes') // -1
vehicles.indexOf('Trains') // 2
The findIndex
method is not supported in older browsers. This method accepts a callback function, which returns an index of the item when the condition inside it returns true
.
const places = ['Toronto', 'Mumbai', 'Melbourne', 'Berlin'];
vehicles.findIndex(place=>place==='New York')
// -1
vehicles.findIndex(place=>place==='Mumbai')
// 1
Related Solutions
Rate this post
Suraj Sharma is the founder of Future Gen AI Services. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.