Home  >  Article  >  Web Front-end  >  How to Find All Occurrences of an Element in a JavaScript Array?

How to Find All Occurrences of an Element in a JavaScript Array?

Barbara Streisand
Barbara StreisandOriginal
2024-10-30 02:56:28450browse

How to Find All Occurrences of an Element in a JavaScript Array?

Retrieve Indexes of Element Occurrences in Array

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn