admin管理员组

文章数量:1302272

Say I have two arrays:

const data = [1, 2, 3, 4]
const predicateArray = [true, false, false, true]

I want the return value to be:

[1, 4]

So far, I have e up with:

pipe(
  zipWith((fst, scnd) => scnd ? fst : null)),
  reject(isNil) 
)(data, predicateArray)

Is there a cleaner / inbuilt method of doing this?

Solution in Ramda is preferred.

Say I have two arrays:

const data = [1, 2, 3, 4]
const predicateArray = [true, false, false, true]

I want the return value to be:

[1, 4]

So far, I have e up with:

pipe(
  zipWith((fst, scnd) => scnd ? fst : null)),
  reject(isNil) 
)(data, predicateArray)

Is there a cleaner / inbuilt method of doing this?

Solution in Ramda is preferred.

Share asked Apr 7, 2017 at 9:53 jgr0jgr0 7272 gold badges7 silver badges21 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 11

This works in native JS (ES2016):

const results = data.filter((d, ind) => predicateArray[ind])

If you really want a Ramda solution for some reason, a variant of the answer from richsilv is simple enough:

R.addIndex(R.filter)((item, idx) => predicateArray[idx], data)

Ramda does not include an index parameter to its list function callbacks, for some good reasons, but addIndex inserts them.

As asked, with ramda.js :

const data = [1, 2, 3, 4];
const predicateArray = [true, false, false, true];

R.addIndex(R.filter)(function(el, index) {
  return predicateArray[index];
}, data); //=> [2, 4]

Updated example to fix issue referenced in the ment.

本文标签: javascriptFiltering an Array based on another Boolean arrayStack Overflow