How to Find an Array Index by Value Using JavaScript?

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

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.