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?

3
  • Maybe just slice the array at the current index first? Not entirely clear what you're trying to achieve Commented Feb 15, 2019 at 9:40
  • Could you show us expected results for an input of [0, 1, 2, 0, 1, 2]? Commented Feb 15, 2019 at 9: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. Commented Feb 15, 2019 at 10:00

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

-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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.