0

I couldn't find that in the documentation, is there a built in simple way to subset an array using a boolean array for filtering? In lodash or es6

I used to use this feature in R a lot and it seemed to be quite useful. Lately I faced several use cases when I could use something like that but couldn't find out if it is supported out of the box.

something like

subset([1, 2, 3, 4, 5], [true, false, false, false, true]) // => [1, 5]

3 Answers 3

2

A quick way of doing this would be something like

const f = (as, bs) => as.filter((_, i) => bs[i])
f([1, 2, 3, 4, 5], [true, false, false, false, true])  // => [1, 5]

This assumes that the two arrays have the same length, which might or might not be what you want.

Sign up to request clarification or add additional context in comments.

2 Comments

It doesn't matter if they have the same length. Since undefined is a falsy value. It will only include the length of the filter array.
What if the default assumption was to include the value instead? That wouldn't work. I'm just saying that calling this function with two arrays of different length doesn't make much sense if you don't specify the exact semantics
1

const arr = [1, 2, 3, 4, 5];
const filter = [true, false, false, false, true];

const result = arr.filter((r, i) => filter[i]);
console.log(result);

You can use built in filter array function. It has a signature which accepts an index also you can use it to filter your array as below :

Comments

0

How about the following?

zip=rows=>rows[0].map((_,c)=>rows.map(row=>row[c]))
zip([[1, 2, 3, 4, 5], [true, false, false, false, true]]).filter(e => e[1])
// [ [ 1, true ], [ 5, true ] ]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.