How to find the index of a value in an array in JS?
October 26, 2018
If you have an array of values, and you want to know what index a certain value has, you can use this:
const fruits = ["apple","banana","orange","grapes"];
console.log(fruits.indexOf("orange")); //returns 2, as it is the 3rd item in array but array index starts at 0
If you want to search with a predicate function, you can use findIndex
which will return the index of the first item which the predicate returns true:
const people = [
{ nationality: 'British', name: 'Fred', },
{ nationality: 'French', name: 'Aimée',}
];
console.log(people.findIndex(person => person.nationality === 'French'));
// { nationality: 'French', name: 'Aimée', }