Sometimes, we want to return index value from filter method with JavaScript.
In this article, we’ll look at how to return index value from filter method with JavaScript.
How to return index value from filter method with JavaScript?
To return index value from filter method with JavaScript, we use the findIndex
method.
For instance, we write
const data = [];
const fieldId = 5;
const index = data.findIndex((x) => x.id === fieldId);
to call data.findIndex
with a callback to get the value with id
set to fieldId
.
The index
of the first item in data
that matches the condition will be returned.
Conclusion
To return index value from filter method with JavaScript, we use the findIndex
method.