Sometimes, we want to find index of all occurrences of element in array with JavaScript.
In this article, we’ll look at how to find index of all occurrences of element in array with JavaScript.
How to find index of all occurrences of element in array with JavaScript?
To find index of all occurrences of element in array with JavaScript, we can use the array map
method.
For instance, we write
const indices = array.map((e, i) => (e === value ? i : "")).filter(String);
to call array.map
to return all the indices of all the items in array
that’s equal to value
.
If entry e
equals value
, then we return the index i
of it.
Then we call filter
with string to filter out any non-number entries.
Conclusion
To find index of all occurrences of element in array with JavaScript, we can use the array map
method.