Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split an array into sublists with Ramda?

Tags:

ramda.js

This is the initial state.

const All = { 
  id : [ "a", "b", "c", "d", "e"],
  count : [1, 2, 2],
}

I want All.id split into [ ["a"], ["b", "c"], ["d", "e"]] by using the All.count

I tried R.map(R.take(All.count), All.id). But this is not working.

What I am missing here?

like image 675
Rio Avatar asked Oct 30 '25 09:10

Rio


1 Answers

You can use R.mapAccum to slice the section between the current and previous position, and to preserve the previous position in the accumulator. Use R.last to take the resulting array (the 1st item is the accumulator).

const { pipe, mapAccum, slice, last } = R

const fn = ({ id, count }) => pipe(
  mapAccum((acc, v) => [acc + v, slice(acc, acc + v, id)], 0),
  last
)(count)

const All = { id : [ "a", "b", "c", "d", "e"], count : [1, 2, 2] }

const result = fn(All)

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.1/ramda.min.js" integrity="sha512-rZHvUXcc1zWKsxm7rJ8lVQuIr1oOmm7cShlvpV0gWf0RvbcJN6x96al/Rp2L2BI4a4ZkT2/YfVe/8YvB2UHzQw==" crossorigin="anonymous"></script>
like image 150
Ori Drori Avatar answered Nov 02 '25 23:11

Ori Drori