应用“sortBy”产生意外结果。
我必须做一些愚蠢的事情。这是一个基本的操作。
const input = [4,3,2,1];
const sort = list => R.sortBy(R.ascend(R.identity))(list);
console.log(sort(input)); // [ 4, 3, 2, 1 ]
我期望“console.log”调用的输出为 [ 1, 2, 3, 4 ],但事实并非如此:输出为 [ 4, 3, 2, 1 ],与输入相同。我究竟做错了什么?
最佳答案
正如 Aadit M Shah 在评论中指出的,您没有使用 sortBy
正确。
以下是如何在 Ramda 中排序的快速概述:
排序
Returns a copy of the list, sorted according to the comparator function, which should accept two values at a time and return a negative number if the first value is smaller, a positive number if it's larger, and zero if they are equal.
一例使用 subtract
按升序排序:
sort(subtract, [4, 1, 2, 3]);
//=> [1, 2, 3, 4]
或者按降序排序,只需 flip
它:
sort(flip(subtract), [4, 1, 2, 3]);
//=> [4, 3, 2, 1]
sort
只是期望一个可以接受两个参数的函数,可以与 <
进行比较或>
.
那么如何对字符串数组进行排序呢?字符串可以与 <
进行比较或>
但使用 subtract
没有意义。这就是 ascend
(或 descend
)可能很有用:
Makes an ascending comparator function out of a function that returns a value that can be compared with < and >.
sort(ascend(identity), ["b", "a", "B", "A"]);
//=> ["A", "B", "a", "b"]
如果您想进行不区分大小写的比较:
sort(ascend(toLower), ["b", "a", "B", "A"]);
//=> ["a", "A", "b", "B"]
排序依据
正如我们所见,sort
期望您为其提供一个接受两个参数的函数,这两个参数可以使用 <
进行比较。或>
。数字和字符串可以与这些运算符进行比较,因此如果您可以直接将它们提供给 Ramda,那么:
sortBy(identity, [4, 1, 2, 3]);
//=> [1, 2, 3, 4]
等同于:
sort(subtract, [4, 1, 2, 3]);
//=> [1, 2, 3, 4]
但是据我所知,sortBy
总是按升序对事物进行排序。
排序
您使用sortWith
当您可以有多个排序条件时:
- 按年龄升序排列
- 按名称降序排列
sortWith([ascend(prop('age')), descend(prop('name'))], [
{age: 40, name: 'John'},
{age: 40, name: 'Zack'},
{age: 10, name: 'Liam'},
{age: 20, name: 'Bill'}
]);
//=> [
//=> {age: 10, name: "Liam"},
//=> {age: 20, name: "Bill"},
//=> {age: 40, name: "Zack"},
//=> {age: 40, name: "John"}
//=> ]
关于javascript - Ramda 的意外 'sortBy' 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56105016/