Shrey Gupta
Shrey Gupta

Reputation: 5617

How to get index of all occurences of the same value in an Array?

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.)

Upvotes: 6

Views: 14003

Answers (4)

Bungus
Bungus

Reputation: 602

@Bagavatu: If you don't want a for loop you could try this fiddle -

var dataset = [2,2,4,2,6,4,7,8];
var results = [];

var ind

// the while loop stops when there are no more found
while( ( ind = dataset.indexOf( 2 ) ) != -1 ){
    results.push( ind + results.length )
    dataset.splice( ind, 1 )
}

return results;

NOTE: using a for loop would be MUCH quicker. See comments.

var dataset = [2,2,4,2,6,4,7,8];
var results = [];
for ( i=0; i < dataset.length; i++ ){
    if ( dataset[i] == 2 ){
        results.push( i );
    }
}

return results;

Upvotes: 3

Igor
Igor

Reputation: 33983

Looks like this functionality may not be possible out-of-the-box, but there is a 'plugin' available here by creating a Array.prototype.allIndexOf function.

It still iterates over the entire list (which is required), but it abstracts the logic a little bit.

Upvotes: 1

maqjav
maqjav

Reputation: 2434

Here you have an example: Try if yourself

var dataset = [2,2,4,2,6,4,7,8];

// We get the first indexOf number 2
var prev = dataset.indexOf(2);

// While we find indexes we keep searching
while (prev != -1) { 
    alert(prev);
    // we get the indexOf number 2 starting in the previous position + 1
    prev = dataset.indexOf(2, prev + 1);
}

Upvotes: 1

faino
faino

Reputation: 3224

You can use the filter() method of the Array object to handle nicely:

var dataset = [2, 2, 4, 2, 6, 4, 7, 8];
var indexs = [];
dataset.filter(function(elem, index, array){
    if(elem == 2) {
        indexs.push(index);
    }
});
alert(indexs);

And here is some more documentation on the filter() method, as well as a fallback for older browsers.

Upvotes: 3

Related Questions