How to Find the Index of All Occurrences of a Value in JavaScript?

Estimated read time 2 min read

To find the index of all occurrences of a value in a JavaScript array, you can use a loop and the indexOf method. The indexOf method can be used to check if a value is present in an array and return its index.

Here’s an example:

const array = [1, 2, 3, 4, 5, 1, 6, 1];
const value = 1;
const indices = [];

let index = array.indexOf(value);
while (index !== -1) {
  indices.push(index);
  index = array.indexOf(value, index + 1);
}

console.log(indices); // Output: [0, 5, 7]

In this example, the indexOf method is used in a loop to find all occurrences of the value 1 in the array. The indexOf method is called with two arguments: the target value and the start index. In the first iteration, the indexOf method is called with just the target value, and it returns the first index of the target value in the array, which is 0. In subsequent iterations, the indexOf method is called with the target value and the start index of the previous occurrence, and it returns the next occurrence of the target value in the array, if any. The loop continues until the indexOf method returns -1, which means that no more occurrences of the target value are found in the array. The indices of all occurrences of the target value are stored in the indices array.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply