[英]Filtering an Array based on another Boolean array
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 come 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. Ramda 中的解决方案是首选。
这适用于原生 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:如果出于某种原因你真的想要一个 Ramda 解决方案,richsilv 的答案的一个变体很简单:
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. Ramda 没有在其列表函数回调中包含
index
参数,这是有充分理由的,但addIndex
插入它们。
As asked, with ramda.js
:正如所问,使用
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 comment.更新示例以修复评论中引用的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.