基于另一个布尔数组过滤一个数组

Filtering an Array based on another Boolean array

假设我有两个数组:

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

我希望 return 值为:

[1, 4]

到目前为止,我想出了:

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

是否有更清洁/内置的方法来执行此操作?

首选 Ramda 解决方案。

这适用于原生 JS (ES2016):

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

根据要求,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]

更新示例以解决评论中提到的问题。

如果出于某种原因你真的想要一个 Ramda 解决方案,那么 richsilv 的答案变体就足够简单了:

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

Ramda 不在其列表函数回调中包含 index 参数,出于某些充分的原因,但 addIndex 插入了它们。