1

I'm trying to make indexOf return me multiple indexes of array's items which value equal "1" (exactly matching).

Here's what I'm doing:

var arr = [1, 11, 1, 111, 1111, 11, 1, 1111, 11];
for (i = 0; i < arr.length; i++){
  console.log(arr.findIndex(1, i));
}

Result which I expect is: 0 2 6

But actually I get "-1" value after mentioned indexes. I'm assuming that it's related to array's values (each of them include "1" but not equals to "1"). When I'm doing the same with array of different values, it works as desired.

Does it really related to values? If yes, how to solve this problem? If there are more proper ways to find multiple array's indexes by a value (with exact match), it would be much appreciated.

zatvornik
  • 171
  • 1
  • 3
  • 8
  • 1
    Possible duplicate of [How to find index of all occurrences of element in array?](https://stackoverflow.com/questions/20798477/how-to-find-index-of-all-occurrences-of-element-in-array) – stdob-- Sep 03 '18 at 17:53

2 Answers2

6

You can reduce the array to array of indexes, which value is 1:

const arr = [1, 11, 1, 111, 1111, 11, 1, 1111, 11];

const indexes = arr.reduce((r, n, i) => {
  n === 1 && r.push(i);
  
  return r;
}, []);

console.log(indexes);

You can also use indexOf and a while loop, to start search from the last found index, and stop when the index is -1:

const arr = [1, 11, 1, 111, 1111, 11, 1, 1111, 11];

let i = -1;
const indexes = [];

while(i = arr.indexOf(1, i + 1), i !== -1) indexes.push(i);

console.log(indexes);
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
3

There are multiple ways to do it with Pure JavaScript. I've added some of them.

Using Array.prototype.filter()

var arr = [1, 11, 1, 111, 1111, 11, 1, 1111, 11];
var keys = [];
var filtered = arr.filter((e, i) => {
  if (e === 1) {
    keys.push(i);
  }
});
console.log(keys);

Using Array.prototype.forEach()

var arr = [1, 11, 1, 111, 1111, 11, 1, 1111, 11];
var keys = [];
arr.forEach((e,i)=>{
  if(e === 1){
    keys.push(i);
  }
});
console.log(keys);

Using Array.prototype.reduce()

var arr = [1, 11, 1, 111, 1111, 11, 1, 1111, 11];
var keys = [];
arr.reduce(function(a, e, i) {
  if (e === 1)
    keys.push(i);
  return keys;
}, [])

console.log(keys);
A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103