EN
JavaScript - find indexes of all occurrences of element in array
0
points
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]