Using JavaScript's indexOf method with multiple search values

I have a data set that includes various duplicate values

["test234", "test9495", "test234", "test93992", "test234"]

I am looking to find the positions of every instance of test234 in the dataset

Although I've attempted using the Array.prototype.indexOf() method, it only gives me the first occurrence at index 0, while I actually need it to provide all the indices such as [0, 2, 4].

Is there a way to achieve this?

var array = ["test234", "test9495", "test234", "test93992", "test234"];
document.write(array.indexOf("test234"));

Answer №1

To efficiently go through each element in an array, use a for loop.

var array = ["test234", "test9495", "test234", "test93992", "test234"];

for (i=0;i<array.length;i++) {
  if (array[i] == "test234") {
    document.write(i + "<br>");
  }
}

Answer №2

While there isn't a built-in function for this specific task, creating your own is quite simple to do. Luckily, the indexOf method can be used with a starting index as its second parameter.

function findIndexes(array, searchValue) {
  var i = array.indexOf(searchValue);
  var indexes = [];
  
  while (i !== -1) {
    indexes.push(i);
    i = array.indexOf(searchValue, ++i);
  }
  
  return indexes;
}

var array = ["test234", "test9495", "test234", "test93992", "test234"];
document.write(JSON.stringify(findIndexes(array, "test234")));

Answer №3

If you're looking to find the indexes of a specific item in an array, you can achieve this using the reduce method:

const indexesOf = (arr, item) => 
  arr.reduce(
    (acc, v, i) => (v === item && acc.push(i), acc),
  []);

For example:

const array = ["test234", "test9495", "test234", "test93992", "test234"];
console.log(indexesOf(array, "test234")); // [0, 2, 4]

Another approach is to use an iterator:

function* finder(array, item) {
  let index = -1;
  while ((index = array.indexOf(item, index + 1)) > -1) {
    yield index;
  }
  return -1;
}

This allows for lazy searching, only retrieving indexes when needed:

let findTest234 = finder(array, "test234");

console.log(findTest234.next()) // {value: 0, done: false}
console.log(findTest234.next()) // {value: 2, done: false}
console.log(findTest234.next()) // {value: 4, done: false}    
console.log(findTest234.next()) // {value: -1, done: true}

The iterator can also be used in loops:

let indexes = finder(array, "test234");

for (let index of indexes) {
   console.log(index);
}

To generate arrays immediately, you can consume the iterator like so:

let indexes = [...finder(array, "test234")];
console.log(indexes); // [0, 2, 4]

I hope this solution is helpful for your needs.

Answer №4

To locate a specific value in an array in JavaScript, you can leverage the fromIndex parameter of the Array#indexOf method.

fromIndex

The fromIndex is used to specify the starting point for the search in the array. If the provided index is equal to or greater than the array's length, the method returns -1 indicating that the array will not be searched. When a negative value is passed as the index, it indicates an offset from the end of the array. It's important to note that even if a negative index is used, the search will still occur from front to back. If the calculated index is less than 0, the entire array will be searched. By default, the entire array is searched starting at index 0.

The operator ~ is known as a bitwise not operator, and it can be effectively utilized with the indexOf() method. This is because indexOf returns the index of the found value (between 0 and n) or -1 if the value is not found:

Here's a quick explanation:

value  ~value   boolean
-1  =>   0  =>  false
 0  =>  -1  =>  true
 1  =>  -2  =>  true
 2  =>  -3  =>  true
 and so on 

var array = ["test234", "test9495", "test234", "test93992", "test234"],
    result = [],
    pos = array.indexOf('test234');

while (~pos) {
    result.push(pos);
    pos = array.indexOf('test234', pos + 1); // utilize the previous position incremented
} //                               ^^^^^^^

document.write('<pre> ' + JSON.stringify(result, 0, 4) + '</pre>');

Answer №5

To retrieve the index values of 0,2,4 using a for loop and indexOf, follow this code snippet:

let items = ["apple", "banana", "apple", "kiwi", "apple"];
let indexes=[];
for (i=0;i<items.length;i++) {
  if (items[i].indexOf("apple") >=0 ) {
    indexes.push(i);
  }
}
document.write(indexes);

Answer №6

Although not the perfect solution, I decided to experiment with a recursive approach:

const findIndexes = (arr, target, start = 0) => {
  let indexes = [];

  //Handle edge cases
  if(!target || !arr || arr.length <= start) return indexes;

  //Find index of target element starting from specified position
  let index = arr.indexOf(target, start);

  //If index is not found, return empty array
  if(index < 0) return indexes;

  //Insert the index into the result array
  indexes.push(index);

  //Recursively call the function with updated start index
  indexes = indexes.concat(findIndexes(arr, target, ++index));

  //Return array containing all found indexes
  return indexes;
}

const elements = ["apple", "orange", "banana", "apple"];
console.log(findIndexes(elements, "apple")); 
//Output: [0, 3]

Answer №7

Here is a JavaScript function that finds the indexes of a specific string within an array:

function getIndexPositions(str, arr){
        var positions = [];
        for (var i=0; i<arr.length; i++) {
            if (str === arr[i]) {
                positions.push(i);
            }
        }
        return positions;
    }

var myArray = ["apple", "banana", "orange", "banana", "grape"];
var searchString = "banana";
console.log(getIndexPositions(searchString, myArray));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Do external JavaScript files exclusively serve as repositories for functions?

Hey there, I'm a beginner in Web Development and I have a question that might sound silly: If I decide to keep my scripts in an external .js file, would it essentially just serve as a container for functions? For instance, if I attempt to include cod ...

Disabling a Field in Angular While Preserving its Value

Hey there, late night folks! I have a quick question about Angular. I'm working with a form that includes a specific field where I set the value using patchValue, but I also need to disable this field. The issue is that after disabling it, the value i ...

Guidelines for incorporating a router into the title of a Vuetify.js toolbar

I am currently utilizing vuetify.js in my project and I encountered an issue. I wanted the application title to link to the top menu, but when navigating to /route shop and /discount, the HogeHoge button's state changed unexpectedly. Is there a soluti ...

Are your Express routes failing to function properly?

I recently embarked on creating a new Express app by following the tutorial from Code Magazine. Below are my app and the defined route for /img. https://i.sstatic.net/G6PUG.png Upon trying to access http://localhost:3000/img or http://localhost:3000/img/ ...

How do I access Google Chrome and perform a Google image search within a Node.js/Electron program?

I am currently working on incorporating Google Image search into my Electron-based photo application. My goal is to have users click on a button labeled "Search Google for Image," which will then open up Chrome (if installed) with the local image file in ...

Activate JavaScript functions by pressing the enter key, allowing for various searches, AJAX requests, and DataTable displays to occur seamlessly without the need to refresh

I recently developed a web page that integrates an AWS API interface to interact with an RDS Aurora MySQL Serverless database. Users can input a SQL statement and click the Query button, which triggers an AJAX request, returns JSON data, and converts the d ...

How do three buttons display identical content?

I have three buttons on my website, each with its own unique content that should display in a modal when clicked. However, I am experiencing an issue where regardless of which button I click, the same content from the last button added is displayed in the ...

What is causing the discrepancy in functionality between these two HTML/CSS files with identical code?

In this codepen, you'll find the first example: Subpar Pen: https://codepen.io/anon/pen/jGpxrp Additionally, here is the code for the second example: Excellent Pen: https://codepen.io/anon/pen/QqBmWK?editors=1100 I'm puzzled why the buttons l ...

Automating the process of posting a file to a form with javascript

I have a piece of client-side JavaScript that creates a jpeg file through HTML5 canvas manipulation when the user clicks an "OK" button. My goal is to automatically insert this jpeg output into the "Upload Front Side" field in a form, simulating a user up ...

Conceal the div element five seconds after the registration process is completed

Is it possible to automatically hide a div 5 seconds after a user registers? Using the timestamp in PHP for the user's registration, there may be a way to achieve this with jQuery, but it's not certain. I found a script online that successfully ...

Tips for configuring Visual Studio Code to utilize path mappings for handling automatic imports

In order to streamline my project and avoid messy paths, I am implementing absolute paths that will allow for consistent imports regardless of the file's location in the project tree. For this purpose, I made adjustments to the tsconfig.json: "paths ...

Selecting elements by class in jQuery using a variable for the class name

Is there a way in jQuery to apply actions to all elements with a specific class, where the class name is determined by a variable? I want to select elements based on this dynamically generated class name. var x = $(this).attr('href').slice(1); ...

What causes CSS to fail to load in React but work normally in Next.js?

We are currently experiencing an issue with a component located in a Git Submodule that is being used by both Next.js and React. While everything is functioning correctly in Next.js, React is unable to accept the way the CSS is being loaded: import styles ...

When the 'keyup' event is detected, trigger the function only on keyup

Looking for assistance in setting this to only trigger on keyup events. Can anyone provide guidance? $(function() { $('#acf-field_5a32085c7df98-field_5a3208f87df99').on('keyup', function() { $('#link-headline-fb').text($( ...

Breaking down a large array in Node.js to initiate multiple API calls

I am currently faced with a challenge where I have a CSV file containing 21k records, with each record being a single alphanumeric word. I need to process these records by sending them to an API in JSON key-value pair format. The API can only accept 500 el ...

Quick way to specify type for Observable in Typescript

Exploring Shortcut Declarations When working with TypeScript, I often take a shortcut when declaring object shapes. Instead of creating an interface first and then specifying that the object conforms to that type, I simply do: object: { fizz: boolean, buz ...

The command is not currently carrying out its function

I am attempting to verify whether the "sender" has either of the two specified roles, but for some reason the command is not being executed. There are no errors showing up in the console, it's just that the command doesn't run. const revAmount = ...

Poor quality picture captured with the use of the getUserMedia() Javascript function

Is there a way to improve the resolution of mobile phone camera screenshots taken with JavaScript's getUserMedia function? if (navigator.mediaDevices) { navigator.mediaDevices.getUserMedia({ video: { width: { min: 1280, }, heig ...

Custom Component in React Bootstrap with Overflowing Column

I am working on a custom toggle dropdown feature in my React application: import React from 'react'; import 'react-datepicker/dist/react-datepicker.css'; const DateRange = props => ( <div className="dropdown artesianDropdo ...

What steps should I take to create this animation?

So here's my concept: I envision a circle div positioned in the center with multiple small lines extending outwards, resembling rays of sunlight. How should I go about achieving this effect? Would implementing JavaScript or utilizing CSS3 animations b ...