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 badges3 Answers
Reset to default 11This 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
版权声明:本文标题:javascript - Filtering an Array based on another Boolean array - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741663208a2391159.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论