Categories
JavaScript Answers

How to find index of all occurrences of element in array?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.