0

I would like to take an array and split it into a dictionary of sub-arrays based on another array of indices:

const arr = ["A", "B", "C", "D", "E"];
const indices = [0, 0, 1, 0, 3];
    
// Would like to do something like this:
R.split(indices, array) // { "0": ["A", "B", "D"], "1": ["C"], "3": ["E"] }

Is there an elegant way to do this in Ramda?

1 Answer 1

2

Use R.zip combine the arrays to an array of values/indices pairs. Group by the indices, and then take only the values from the pairs:

const { pipe, zip, groupBy, last, map, head } = R

const fn = pipe(
  zip, // combine the arrays to an array of value/indice pairs
  groupBy(last), // group by the indices
  map(map(head)) // take only the values from the pairs
)

const arr = ["A", "B", "C", "D", "E"]
const indices = [0, 0, 1, 0, 3]

const result = fn(arr, indices)

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.28.0/ramda.min.js" integrity="sha512-t0vPcE8ynwIFovsylwUuLPIbdhDj6fav2prN9fEu/VYBupsmrmk9x43Hvnt+Mgn2h5YPSJOk7PMo9zIeGedD1A==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

Sign up to request clarification or add additional context in comments.

Comments

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.