To find index of all occurrences of element in array, we use the map
and filter
method.
For instance, we write
const nanoIndexes = cars
.map((car, i) => (car === "Nano" ? i : -1))
.filter((index) => index !== -1);
to call map
with a callback that checks if the car
value being iterated through is 'Nano'
.
If it is, we return i
and we return -1 otherwise.
Then we call filter
with a callback that returns an array with the index
value not equal to -1.