In this post, we are going to understand Array findindex in ES6 JavaScript with example.The array.findindex() method is introduced in ES6.Befor understand this function in details will go through the difference between array.findindex() and array.indexof().
Array.indexof() : This function takes the value as the first argument and finds the index of an array of primitive types(string, number, or boolean). if we are looking to find the index for simple values like numbers or strings then an array.indexof() is the fastest to use. We can’t pass a predicate to array.indexof().If pass a callback function to an array.index() will return -1.
The array.findindex() accept the callback function as the first argument return index of the non-primitive type or complex type like object that satisfies the given condition set by a callback function. We can find an index of a given element by searching the key value of the property of the object.
Passing a value to findindex() will throw an error.
Let us understand find an array of objects in JavaScript with below examples
1. Findindex() Method to find array of objects in javaScript
In ES6, Findindex() is a new method added in Array. Prototype returns the index of the first element of the array of object which satisfies the given condition set by a callback function, otherwise, returns -1 if no element of the array satisfies the condition.
Syntax
array.findIndex(callback( element[, index[, array]] )[, thisArg])
Parameters
- Callback: Call on each element of the array. The callback function takes these three-arguments.
- Element: it represents the current element.
- index: It represents the index of the current element.
- Array: It represents the array on we are calling the find() method.
- thisarg: It is an optional parameter. It is a value that is used as this while using callback.
Program to find index of Array of objects in javaScript
In this example, we are using the array.findIndex() method with a callback function that checks if (item. item === ‘Graphes’) and returns the first element in the array that satisfy this given condition.
let groceries = [
{
item: 'Apple',
prize: 80,
Quantity:20,
purchasedDate: 'December 3, 2019'
},
{
item: 'Graphes',
prize: 100,
Quantity:10,
purchasedDate: 'December 21, 2020'
}
];
let indx = groceries.findIndex( item => {
if (item.item === 'Graphes') {
return true;
}
});
console.log('The index of value Graphes :',indx);
Output
The index of value Graphes : 1