We can find indexes of all occurrences of an element in a JavaScript array by using the JavaScript array’s reduce
method.
For instance, we can write:
const arr = ["Nano", "Volvo", "BMW", "Nano", "VW", "Nano"].reduce((a, e, i) => {
if (e === 'Nano')
a.push(i);
return a;
}, []);
console.log(arr)
to call reduce
on the array where we want to get all indexes of the string 'Nano'
from.
To do that, we call it with a callback that takes the a
array that we’re going to push the indexes into.
e
has the entry of the array we’re checking to see if it’s 'Nano'
.
And i
is the index of the array entry e
.
If e
is 'Nano'
, we call push
with i
to push i
into the a
array.
And then we return a
.
The 2nd argument is the initial value of a
which is set to an empty array.
And so arr
is [0, 3, 5]
.