I am using a set of numerical values in an array where certain values are be repeated. I want to find the indices of ALL of the occurrences of a repeated value.
For example, I have the following code using indexOf()
:
var dataset = [2,2,4,2,6,4,7,8];
return dataset.indexOf(2);
But this only gives the index of the first occurrence of 2
. (i.e. it returns the value 0
.)
However, I want the indices for ALL the occurrences of 2
to be returned (i.e. 0,1,3
). How can I do this? (I know I could use a for
loop, but I'm wondering if there's a better way to do this having without iterating through the whole array. Basically, I'm trying to save the overhead of explicitly iterating through the whole array.)
for
loop iteration. – Pugliese