Reputation: 1107
I wrote the below function which on a given array and value will return array of the indexes of the value in the array. I observed that it is working only for certain elements?
var arr = [1,2,3,1,2,3,3,4,3]
var findAll = function(arr, val) {
var results = [];
var length = arr.length;
var pos = 0;
while(pos < length) {
pos = arr.indexOf(val, pos);
if (pos == -1) return [];
results.push(pos);
pos = pos + 1;
}
return results;
}
//Output:
findAll(arr,3)
[2, 5, 6, 8]
findAll(arr,1)
[] // expected [0,3]
findAll(arr,2)
[] // expected [1,4]
findAll(arr,4)
[] // expected [7]
Upvotes: 0
Views: 87
Reputation: 406
This is how to do it. Simply. And doesn't iterate through the whole array.
function check(ar, val){
var pos = 0;
var tmp = [];
pos = ar.indexOf(val, pos);
while (pos >= 0){
tmp.push(pos);
pos = ar.indexOf(val, pos + 1);
}
return tmp;
Upvotes: 0
Reputation: 7372
the problem you keep on searching till the end of array. if you dont find something you return [].
so if the value you search for is not the last element in array you'll get []
you should change your if to:
if (pos != -1) results.push(pos);
Upvotes: 2
Reputation: 72857
Let's give the function a quick rewrite. This is all you need:
var findAll = function(arr, val) {
var results = [];
for(var i = 0; i < arr.length; i++){ // Loop through the array.
if(arr[i] === val){ // If the desired value is found
results.push(i); // Push it's index to `results`
}
}
return results;
}
It's probably not the most efficient, since it iterates the entire array no matter what, but it works like a charm.
Upvotes: 1
Reputation: 17710
The problem is this line:
if (pos == -1) return [];
You should replace it with:
if (pos == -1) break;
or possibly:
if (pos == -1) return results;
Upvotes: 0