0

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?

Chetan Kumar
  • 427
  • 1
  • 3
  • 18
  • Maybe just `slice` the array at the current index first? Not entirely clear what you're trying to achieve – CertainPerformance Feb 15 '19 at 09:40
  • Could you show us expected results for an input of `[0, 1, 2, 0, 1, 2]`? – mjwills Feb 15 '19 at 09:48
  • Given that `arr[0] === arr[1]`, those two values are not distinguishable for `indexOf`. There is no solution - you have to pass around the index itself, not the array value. – Bergi Feb 15 '19 at 10:00

2 Answers2

2

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

R3tep
  • 12,512
  • 10
  • 48
  • 75
-1

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

dileepkumar jami
  • 2,185
  • 12
  • 15