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

3

假设我有两个数组:

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中的解决方案。
3个回答

11

这在本地的JS(ES2016)中有效:

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

“d”参数的目的是什么?它没有被使用,所以…… - Carlos Toscano-Ochoa
1
@CarlosToscano-Ochoa 位置参数不能被跳过。无论它叫什么,你都必须指定它。 - Sebastian Simon

3
如果你真的因为某种原因想要一个Ramda解决方案,那么richsilv的答案的变体就足够简单了:
R.addIndex(R.filter)((item, idx) => predicateArray[idx], data)

Ramda在其列表函数回调中不包括index参数,这是有一些好的理由的,但addIndex会插入它们。


1
不错的解决方案!您能分享一下为什么没有包括索引的原因吗? - Pablo Navarro
2
恐怕在这里讨论太深入了,但您可以查看相关的 Ramda 问题:452(有争议),4847291061 - Scott Sauyet

0
按要求,使用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]

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


如果数据数组包含重复值,这将无法工作,因为indexOf只会返回第一个索引。 - jgr0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接