繁体   English   中英

根据另一个布尔数组过滤数组

[英]Filtering an Array based on another Boolean array

假设我有两个数组:

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

我希望返回值是:

[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 解决方案,richsilv 的答案的一个变体很简单:

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

Ramda 没有在其列表函数回调中包含index参数,这是有充分理由的,但addIndex插入它们。

正如所问,使用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]

更新示例以修复评论中引用的问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM