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:
xxxxxxxxxx
1
function findIndexes(array, value) {
2
var indexes = [];
3
for (var i = 0; i < array.length; ++i) {
4
if (array[i] === value) {
5
indexes.push(i);
6
}
7
}
8
return indexes;
9
}
10
11
12
// Usage example:
13
14
var letters = ['a', 'b', 'c', 'b'];
15
var result = findIndexes(letters, 'b'); // gets indexes of 'b' occurrences
16
17
console.log(result); // [1, 3]
In this section, we present an alternative solution using Array
reduce()
method to get indexes of all occurrences of 'b'
element in letters
array.
xxxxxxxxxx
1
var letters = ['a', 'b', 'c', 'b'];
2
3
var result = letters.reduce(function(array, value, index) {
4
if (value === 'b') {
5
array.push(index);
6
}
7
return array;
8
}, []);
9
10
console.log(result); // [1, 3]