5

Let's say I have an array with the following values -

var arr = [true, true, false, false, false, true, false];

I'm looking for logic which will give me the following output -

[0,1,5]
balajiprasadb
  • 365
  • 1
  • 5
  • 17
  • 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) – Sudipta Mondal Jun 22 '18 at 06:23
  • You should also post your own effort with the post. – vibhor1997a Jun 22 '18 at 06:35

6 Answers6

12

You can use .reduce() to do this in one pass:

const arr = [true, true, false, false, false, true, false]
const indices = arr.reduce(
  (out, bool, index) => bool ? out.concat(index) : out, 
  []
)
console.log(indices)

You start by passing an empty array [] as the initialValue to .reduce() and use a ternary ? operator to determine whether to .concat() the index or not.


Alternatively, you can use the more recent .flatMap() method:

const arr = [true, true, false, false, false, true, false]
const indices = arr.flatMap((bool, index) => bool ? index : [])
console.log(indices)

If your browser does not yet support it, you'll get an Uncaught TypeError: arr.flatMap is not a function. In that case, you can use my polyfill definition from here.

Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153
3

You could map the indices or for falsy values -1 and then filter all indices which are not -1.

var array = [true, true, false, false, false, true, false],
    result = array
        .map((b, i) => b ? i : -1)
        .filter(i => i !== -1);
        
console.log(result);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
3

A potentially more elegant solution is:

[...arr.keys()].filter(i => arr[i])

or alternatively

[...arr.entries()].filter(([, v]) => v).map(([i]) => i)
Stuart
  • 9,597
  • 1
  • 21
  • 30
0

You can simply use a loop and check the boolean value true in your if condition:

var arr = [true, true, false, false, false, true, false];
var indexArray = [];
arr.forEach((val, index) => {
  if(val){
    indexArray.push(index);
  }
});

console.log(indexArray);
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62
-1

try this

var arr = [true, true, false, false, false, true, false];
var indexArray = [];
arr.forEach(function(value, index) {
    if (value) {
        indexArray.push(index);
    }
})
console.log(indexArray);
Muhammad Usman
  • 10,039
  • 22
  • 39
prady
  • 416
  • 2
  • 6
  • 17
-1

Different solution based on logic itself and not JS paradigms

let newArr = [];
for (let i = 0 ; i<indexArray.length;i++){
    if (indexArray[i]) newArr.push(i)
}
Thenad
  • 155
  • 2
  • 11