How to find indexes of all occurrences of an element in a JavaScript array?

Estimated read time 1 min read

You can use a for loop in JavaScript to find all the indexes of a specific element in an array. Here’s an example:

let arr = [1, 2, 3, 2, 4, 2];
let search = 2;
let indexes = [];

for (let i = 0; i < arr.length; i++) {
  if (arr[i] === search) {
    indexes.push(i);
  }
}

if (indexes.length) {
  console.log(`The element "${search}" can be found at indexes ${indexes.join(', ')}`);
} else {
  console.log(`The element "${search}" could not be found in the array`);
}

This will output The element "2" can be found at indexes 1, 3, 5.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply