Ramda 的意外 'sortBy' 行为

Unexpected 'sortBy' Behavior with Ramda

'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 (or 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"}
//=> ]