How to find the indexes of all occurrences of an element in array?
Categories:
Finding All Occurrences of an Element in a JavaScript Array

Learn various JavaScript and jQuery methods to efficiently locate all indices of a specific element within an array, from basic loops to advanced functional programming.
When working with arrays in JavaScript, a common task is to find not just the first instance of a particular element, but every single index where that element appears. This can be crucial for data processing, UI manipulation, or validating data structures. This article will explore several robust methods to achieve this, catering to different scenarios and preferences, including plain JavaScript and jQuery approaches.
Method 1: Iterating with a for
Loop
The most straightforward and fundamental way to find all occurrences is by iterating through the array using a for
loop. This method gives you explicit control over the iteration process and is highly compatible across all JavaScript environments. You simply check each element against your target value and store the index if a match is found.
function findAllOccurrencesForLoop(arr, element) {
const indices = [];
for (let i = 0; i < arr.length; i++) {
if (arr[i] === element) {
indices.push(i);
}
}
return indices;
}
const myArray = [1, 2, 3, 2, 4, 2, 5];
const target = 2;
const result = findAllOccurrencesForLoop(myArray, target);
console.log(`Indices of ${target}:`, result); // Output: Indices of 2: [1, 3, 5]
Using a for
loop to find all indices of an element.
for
loop approach is highly performant for large arrays as it avoids creating intermediate arrays, unlike some functional methods. It's a solid choice when performance is critical.Method 2: Using Array.prototype.indexOf()
in a Loop
While indexOf()
typically finds only the first occurrence, it can be leveraged in a loop to find subsequent occurrences by providing a fromIndex
argument. This method repeatedly searches the array starting from the index after the last found occurrence until no more matches are found. This approach is often more concise than a traditional for
loop for this specific task.
function findAllOccurrencesIndexOf(arr, element) {
const indices = [];
let idx = arr.indexOf(element, 0);
while (idx !== -1) {
indices.push(idx);
idx = arr.indexOf(element, idx + 1);
}
return indices;
}
const myArray = ['apple', 'banana', 'orange', 'apple', 'grape', 'apple'];
const target = 'apple';
const result = findAllOccurrencesIndexOf(myArray, target);
console.log(`Indices of '${target}':`, result); // Output: Indices of 'apple': [0, 3, 5]
Finding all indices using indexOf()
with a while
loop.
flowchart TD A[Start] --> B{Initialize indices = [], currentIdx = 0}; B --> C{Find next occurrence of element from currentIdx}; C --> D{Is occurrence found? (idx !== -1)}; D -- Yes --> E[Add idx to indices]; E --> F[Set currentIdx = idx + 1]; F --> C; D -- No --> G[Return indices]; G --> H[End];
Flowchart for finding all occurrences using indexOf()
in a loop.
Method 3: Functional Approach with Array.prototype.forEach()
or Array.prototype.reduce()
For those who prefer a more functional programming style, forEach()
or reduce()
can also be used. forEach()
iterates over each element and its index, allowing you to push matching indices to an external array. reduce()
can accumulate the indices into a new array, making it a powerful one-liner for this task.
Using forEach()
function findAllOccurrencesForEach(arr, element) { const indices = []; arr.forEach((item, index) => { if (item === element) { indices.push(index); } }); return indices; }
const data = [true, false, true, true, false];
const target = true;
const result = findAllOccurrencesForEach(data, target);
console.log(Indices of ${target}:
, result); // Output: Indices of true: [0, 2, 3]
Using reduce()
function findAllOccurrencesReduce(arr, element) { return arr.reduce((acc, item, index) => { if (item === element) { acc.push(index); } return acc; }, []); }
const data = ['a', 'b', 'a', 'c', 'a'];
const target = 'a';
const result = findAllOccurrencesReduce(data, target);
console.log(Indices of '${target}':
, result); // Output: Indices of 'a': [0, 2, 4]
forEach()
and reduce()
offer elegant solutions, be mindful that forEach()
doesn't return a value directly, requiring an external array. reduce()
is more self-contained but can be less readable for beginners.Method 4: jQuery Approach (for DOM elements)
If you are working with a collection of DOM elements and need to find specific ones, jQuery provides powerful selectors and iteration methods. While jQuery arrays are not native JavaScript arrays, you can iterate over them using $.each()
or convert them to a native array first. This method is specifically useful when your 'array' is a jQuery object representing a collection of elements.
<!-- HTML Example -->
<!--
<div class="item">One</div>
<div class="item active">Two</div>
<div class="item">Three</div>
<div class="item active">Four</div>
-->
// JavaScript with jQuery
$(document).ready(function() {
const activeIndices = [];
$('.item').each(function(index) {
if ($(this).hasClass('active')) {
activeIndices.push(index);
}
});
console.log('Indices of active items:', activeIndices); // Output: Indices of active items: [1, 3]
// For finding specific text content
const textIndices = [];
const targetText = 'Three';
$('.item').each(function(index) {
if ($(this).text() === targetText) {
textIndices.push(index);
}
});
console.log(`Indices of items with text '${targetText}':`, textIndices); // Output: Indices of items with text 'Three': [2]
});
Using jQuery's $.each()
to find indices of matching DOM elements.