简体   繁体   中英

How to get two arrays by mapping a predicate over an input array with Ramda

Is there a concise way to achieve the same result as the below but:

  • without mutation
  • without iterating over the input array more than once
  • using Ramda (preferably)

I thought about using reduce to update an accumulator object containing the passed/failed arrays, but I'm not sure if there was a smarter/less verbose option

const predicate = i => i % 2 === 0;
const predicatePassed = [];
const predicateFailed = [];

[1, 2, 3, 4].forEach(i => predicate(i) ? predicatePassed.push(i) : predicateFailed.push(i))

// predicatePassed === [2, 4]
// predicateFailed === [1, 3]

You can use R.partition :

 const predicate = i => i % 2 === 0; const [predicatePassed, predicateFailed] = R.partition(predicate)([1, 2, 3, 4]); console.log(predicatePassed); console.log(predicateFailed); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script> 

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM