user2517142
user2517142

Reputation: 341

Finding index of a value in an array

I've been looking around the website and all I find are questions regarding finding the index of a value in an array, but that value is the only occurrence of that value in the array. I was wondering is there was a way to find the index of a repeated value every time that it occurs.

Say there's and array like so:

var arr = [45,56,76,4,53,43,6,273,884,69,47,58,225,222,23,13,89,900,7,66,78,74,69];

Is it possible to loop through this and find the indexes of the value 69?

Upvotes: 1

Views: 138

Answers (6)

Yuan Zhaohao
Yuan Zhaohao

Reputation: 584


var arr = [45,56,76,4,53,43,6,273,884,69,47,58,225,222,23,13,89,900,7,66,78,74,69],
    i = arr.length,
    o = {};

while( i-- ) {
    if( !o[ arr[i] ] ) {  
        `o[ arr[i] ] = [];`
    }
    o[ arr[i] ].push( i );
}

alert( o[69] );

Upvotes: 0

StupidDev
StupidDev

Reputation: 342

My idea

function indexs(arr,val){
    var start = arr.indexOf(val),result = [];
    while(start >= 0){
        result.push(start);
        start = arr.indexOf(val,start+1);
    }
    return result;
}

Have fun :)

Upvotes: 0

user2437417
user2437417

Reputation:

Since we're all posting various ways to perform simple tasks...

var arr = [45,56,76,4,53,43,6,273,884,69,47,58,225,222,23,13,89,900,7,66,78,74,69];

arr.reduce(function(res, n, i) {
    return n === 69 ? res.concat(i) : res;
}, []);

Upvotes: 2

Paul S.
Paul S.

Reputation: 66404

Loop while the next indexOf is not -1..

function allIndicesOf(arr, val) {
    var found = [], i = -1;
    while (-1 !== (i = arr.indexOf(val, i + 1))) found.push(i);
    return found;
}

var arr = [0, 1, 2, 3, 2, 1, 8, 5, 2, 0, 4, 3, 3, 1];

allIndicesOf(arr, 3); // [3, 11, 12]

Upvotes: 1

elclanrs
elclanrs

Reputation: 94151

Here's a way to do it in modern browsers:

function findIndexes(arr, val){
  return arr.map(function(v,i){ return v==val && i }).filter(Number);
}

console.log(findIndexes(arr, 69)); //=> [9,22]

Upvotes: 3

Pointy
Pointy

Reputation: 414086

Of course it's possible. Computers are amazing.

var positions = [];
for (var i = 0; i < arr.length; ++i)
  if (arr[i] === 69)
    positions.push(i);

At the end of that loop, the array "positions" will contain all the indexes of the array where 69 was found.

You could generalize this:

function indexes(arr, value) {
  var rv = [];
  for (var i = 0; i < arr.length; ++i)
    if (arr[i] === value)
      rv.push(i);
  return rv;
}

and then:

var i69 = indexes(arr, 69);

Upvotes: 2

Related Questions