Languages
[Edit]
EN

JavaScript - find indexes of all occurrences of element in array

0 points
Created by:
Rubi-Reyna
677

In this article, we would like to show you how to find indexes of all occurrences of element in array using JavaScript.

Quick solution:

// ONLINE-RUNNER:browser;

function findIndexes(array, value) {
    var indexes = [];
    for (var i = 0; i < array.length; ++i) {
        if (array[i] === value) {
            indexes.push(i);
        }
    }
    return indexes;
}


// Usage example:

var letters = ['a', 'b', 'c', 'b'];
var result = findIndexes(letters, 'b');  // gets indexes of 'b' occurrences

console.log(result);  // [1, 3]

 

Alternative solution

In this section, we present an alternative solution using Array reduce() method to get indexes of all occurrences of 'b' element in letters array.

// ONLINE-RUNNER:browser;

var letters = ['a', 'b', 'c', 'b'];

var result = letters.reduce(function(array, value, index) {
    if (value === 'b') {
        array.push(index);
    }
    return array;
}, []);

console.log(result); // [1, 3]

 

See also

  1. JavaScript - get index of item in array

References

  1. Array.prototype.reduce() - JavaScript | MDN

Alternative titles

  1. JavaScript - get indexes of all occurrences of item in array
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join