ali262883
ali262883

Reputation: 369

Check if values are true in an array and return the indices of those value in typescript

I have an array Box

const box = [ true, false, true, false, true, false, false ];

I want to return the indices if the value is true

For example, in this, it should return [0,2,4].

I have written this code and it is giving error

const box = [ true, false, true, false, true, false, false ];
const index = box.findIndex(x => x ==="true");
console.log(index);

Upvotes: 1

Views: 1623

Answers (3)

Nina Scholz
Nina Scholz

Reputation: 386560

You could take Array#flatMap with either the index or an empty array.

const
    box = [true, false, true, false, true, false, false],
    indices = box.flatMap((b, i) => b ? i : []);

console.log(indices);

Upvotes: 3

Oskar Zanota
Oskar Zanota

Reputation: 500

A simple for loop will do the job:

let indexes = [];
for (let i = 0; i < box.length; i++) {
  if (box[i]) indexes.push(i);
}

Upvotes: 2

Ele
Ele

Reputation: 33726

That code returns -1 because there is not a value equals to "true" as a string.

You can use the function Array.prototype.reduce to generate the desired output as follow:

This is assuming every value is a boolean

const box = [ true, false, true, false, true, false, false ];
const result = box.reduce((r, bool, i) => r.concat(bool ? i : []), []);
console.log(result)

Upvotes: 1

Related Questions