When attempting to locate the positions of multiple instances of an element, such as "Nano," within a JavaScript array, methods like jQuery.inArray or .indexOf() fall short as they only identify the last occurrence.
var Cars = ["Nano", "Volvo", "BMW", "Nano", "VW", "Nano"];
Here's the solution:
The .indexOf() method allows for specifying a starting index, enabling you to loop through the array and pinpoint all instances of the specified value.
<code class="javascript">function getAllIndexes(arr, val) { var indexes = [], i = -1; while ((i = arr.indexOf(val, i + 1)) != -1) { indexes.push(i); } return indexes; } var indexes = getAllIndexes(Cars, "Nano");</code>
However, as pointed out by VisioN in the comments, a straightforward for loop offers a more efficient and concise solution:
<code class="javascript">function getAllIndexes(arr, val) { var indexes = [], i; for (i = 0; i < arr.length; i++) { if (arr[i] === val) { indexes.push(i); } } return indexes; }</code>
The above is the detailed content of How to Find All Occurrences of an Element in a JavaScript Array?. For more information, please follow other related articles on the PHP Chinese website!