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 use the array map
method.
For instance, we write
const indices = array.map((e, i) => (e === value ? i : "")).filter(String);
to call map
with a callback that checks if array
entry e
is equal to value
.
If it is, we return i
.
Otherwise, we return an empty string.
And we call filter
with String
to filter out all the empty strings since they’re falsy.
Conclusion
To find index of all occurrences of element in array with JavaScript, we use the array map
method.