Home >Web Front-end >JS Tutorial >How to Find All Indexes of an Element in a JavaScript Array?
Identifying the indexes of all instances of an element within an array is a common programming task. In JavaScript, arrays offer methods like .indexOf() and .includes(), but they only return the first or last occurrence. To obtain indexes for all instances, a different approach is required.
One effective method involves iteratively checking for element occurrences using .indexOf(). The following function demonstrates this approach:
<code class="js">function getAllIndexes(arr, val) { var indexes = [], i = -1; while ((i = arr.indexOf(val, i + 1)) != -1) { indexes.push(i); } return indexes; }</code>
In this function, the .indexOf() method is repeatedly called with an increasing starting index. Each time it finds an instance of the given value, the corresponding index is added to the indexes array.
Another efficient method is a simple for loop:
<code class="js">function getAllIndexes(arr, val) { var indexes = [], i; for (i = 0; i < arr.length; i++) { if (arr[i] === val) { indexes.push(i); } } return indexes; }</code>
This for loop iterates through the array, comparing each element to the specified value. When a match is found, the loop adds its index to the indexes array.
Both of these approaches can be used to find the indexes of all occurrences of the element "Nano" in the array Cars:
<code class="js">var Cars = ["Nano", "Volvo", "BMW", "Nano", "VW", "Nano"]; var indexes = getAllIndexes(Cars, "Nano");</code>
The indexes variable will now contain an array containing the indexes of all instances of "Nano" in the Cars array: [0, 3, 5].
The above is the detailed content of How to Find All Indexes of an Element in a JavaScript Array?. For more information, please follow other related articles on the PHP Chinese website!