Ramda JS 根据两个参数一次从数组中过滤出多个值
Ramda JS filter out multiple values from an array at once based on two arguments
假设我有一个包含 7 个值的数组:
[1.20, 0.50, 2.00, 0.75, 1.20, 0.75, 0.75]
如何使用 Ramda JS 从该数组中删除 3 个最低值,以便它 returns 成为一个新数组:
[1.20, 2.00, 1.20, 0.75]
?
可能还需要从数组中删除 4 个最高值。这就是为什么我要谈论两个论点。
非常感谢!
您需要使用 R.toPairs
将数组转换为 [index, value]
对,然后按值排序(升序或降序到您传递的 sorter
函数),删除最后一项按照dropNum
,然后按原顺序排序,取值:
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>
假设我有一个包含 7 个值的数组:
[1.20, 0.50, 2.00, 0.75, 1.20, 0.75, 0.75]
如何使用 Ramda JS 从该数组中删除 3 个最低值,以便它 returns 成为一个新数组:
[1.20, 2.00, 1.20, 0.75]
?
可能还需要从数组中删除 4 个最高值。这就是为什么我要谈论两个论点。
非常感谢!
您需要使用 R.toPairs
将数组转换为 [index, value]
对,然后按值排序(升序或降序到您传递的 sorter
函数),删除最后一项按照dropNum
,然后按原顺序排序,取值:
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>