Home > Web Front-end > JS Tutorial > body text

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

Barbara Streisand
Release: 2024-10-30 02:56:28
Original
450 people have browsed it

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"];
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!