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.)
To get the index of all occurrences of an element in a JavaScript array: Create an empty array, that will store the indexes. Use a for loop and loop from 0 up to the array's length. For each iteration of the loop, check if the element at that index is equal to the specific element.
Find all indices of an item in list using list. As list. index() returns the index of first occurrence of an item in list. So, to find other occurrences of item in list, we will call list. index() repeatedly with range arguments.
finditer() The finditer function of the regex library can help us perform the task of finding the occurrences of the substring in the target string and the start function can return the resultant index of each of them.
Get the index of elements in the Python loopCreate a NumPy array and iterate over the array to compare the element in the array with the given array. If the element matches print the index.
@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;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With