【问题标题】:Ramda JS filter out multiple values from an array at once based on two argumentsRamda JS 根据两个参数一次过滤出数组中的多个值
【发布时间】:2022-01-29 05:20:29
【问题描述】:

假设我有一个包含 7 个值的数组: [1.20, 0.50, 2.00, 0.75, 1.20, 0.75, 0.75]

如何使用 Ramda JS 从这个数组中去除 3 个最低值,以便它返回一个新数组: [1.20, 2.00, 1.20, 0.75]?

可能还需要从数组中去除 4 个最高值。这就是为什么我要谈论两个论点。

非常感谢!

【问题讨论】:

    标签: arrays filter arguments ramda.js


    【解决方案1】:

    您需要使用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>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-03-13
      • 1970-01-01
      • 2020-04-09
      • 2017-11-29
      • 2022-11-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多