0

Let's say I have an array of 7 values: [1.20, 0.50, 2.00, 0.75, 1.20, 0.75, 0.75]

How can I strip out the 3 lowest values from this array using Ramda JS, so that it returns a new array: [1.20, 2.00, 1.20, 0.75]?

Might as well need to strip out the 4 highest values from the array. That's why I'm talking about two arguments.

Many thanks!

1 Answer 1

1

You'll need to convert the array to [index, value] pairs using R.toPairs, then sort it by the value (ascending or descending to the sorter function you pass), remove the last items according to dropNum, and then sort it back by the original order, and pluck the values:

const { curry, pipe, toPairs, sortWith, descend, ascend, nth, dropLast, sortBy, pluck } = R

const fn = curry((dropNum, sorter, arr) => pipe(
  toPairs, // convert to [index, value] pairs
  sortWith([sorter(nth(1))]), // sort by the value ascending or descending
  dropLast(dropNum), // remove the last items
  sortBy(nth(0)), // sort by index to restore order
  pluck(1) // take the values
)(arr))

const arr = [1.20, 0.50, 2.00, 0.75, 1.20, 0.75, 0.75]

const remove3lowest = fn(3, descend)
const remove4higesht = fn(4, ascend)

console.log(remove3lowest(arr))
console.log(remove4higesht(arr))
.as-console-wrapper { max-height: 100% !important; top: 0; }
<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.