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.
这适用于原生 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 comment.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.