How to Find an Array Index by Value Using JavaScript?

Learn how to find the index of a value in an array

Using indexOf() we can get index of the first matched array element that matches the specified value. If the value does not exist in the array, -1 is returned. For example:

const arr = ['foo', 'bar', 'baz', 'foo', 'qux'];

arr.indexOf('foo'); // 0
arr.indexOf('bar'); // 1
arr.indexOf('baz'); // 2
arr.indexOf('qux'); // 4

arr.indexOf('foobar'); // -1

Similar to indexOf(), we can make use of lastIndexOf() to get index of the last matched array element that matches the specified value. For example:

arr.lastIndexOf('foo'); // 3

Hope you found this post useful. It was published . Please show your love and support by sharing this post.