Home >Web Front-end >JS Tutorial >How to Find All Indexes of an Element in a JavaScript Array?

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

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-01 00:26:02290browse

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

How to Obtain Indexes of Element Occurrences in an 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.

Using a Loop and .indexOf()

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.

Using a Standard For Loop

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.

Example Usage

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!

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