3

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.

3 Answers 3

11

This works in native JS (ES2016):

const results = data.filter((d, ind) => predicateArray[ind])
Sign up to request clarification or add additional context in comments.

2 Comments

What is the purpose of the 'd' parameter? It is not used, so...
@CarlosToscano-Ochoa Positional parameters cannot be skipped. It doesn’t matter what it’s called, you have to specify it.
3

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.

2 Comments

Nice solution! Can you share a bit more about the reasons why the index is not included?
I'm afraid it's too involved to discuss here, but you can see the relevant Ramda issues: 452 (contentious), 484, 729, and 1061
0

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.

1 Comment

This wont work if the data array contains duplicate value, as indexOf will return only the first index

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.