Chetan Kumar
Chetan Kumar

Reputation: 427

How to avoid accessing same index when most values of array are same? Take a look

I am trying to solve a problem related to javascript algorithms. Here's the problem. I want to access the index of an array value by indexOf() method. But I want to know how can I avoid the same index when most values in the array are the same. Take example:

let arr1 = [0, 0, 0, 0, 1, 1];

Now as you can see most of the values are same and indexOf method looks for an index of a given value in the array.

arr1.indexOf(arr1[0]); // 0 arr1.indexOf(arr1[5]); // 5

So, it will return 0 as the system but when I will going to move further to access the next value. Like:

arr1.indexOf(arr1[1]); // 0 arr1.indexOf(arr1[6]); // 5

It returns the same as before. But I want the next index instead of same. Ex:

arr1.indexOf(arr1[1]); // 1

It should return 1 because 0 is already returned one time. So, what is the solution to this?

Upvotes: 0

Views: 257

Answers (2)

R3tep
R3tep

Reputation: 12864

indexOf have a second parameter, the starting index.

You can do :

let arr1 = [0, 0, 0, 0, 1, 1];
console.log(arr1.indexOf(arr1[1], 1)); // 1


Edit

If you want all index for a specific value, like 0 you can do this :

let arr1 = [0, 0, 0, 0, 1, 1];

function getAllIndexes(arr, val) {
  var indexes = [],
    i = -1;
  while ((i = arr.indexOf(val, i + 1)) != -1) {
    indexes.push(i);
  }
  return indexes;
}

var indexes = getAllIndexes(arr1, 0);

console.log(indexes);

With this script you get an array with all index of a value in an array.

Reference of the script : https://stackoverflow.com/a/20798567/3083093

Upvotes: 2

dileepkumar jami
dileepkumar jami

Reputation: 2265

The indexOf(value) method returns the position of the first occurrence of a specified value in a string.

You can use indexOf(value, start). Here, start is the position to start the search

Upvotes: -1

Related Questions