Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Get indices of true values in a boolean array

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]
like image 965
balajiprasadb Avatar asked Aug 26 '26 20:08

balajiprasadb


2 Answers

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.

like image 101
Patrick Roberts Avatar answered Aug 29 '26 08:08

Patrick Roberts


A potentially more elegant solution is:

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

or alternatively

[...arr.entries()].filter(([, v]) => v).map(([i]) => i)
like image 21
Stuart Avatar answered Aug 29 '26 08:08

Stuart



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!