你如何使用 Ramda 对单词数组进行排序?

How do you sort an array of words with Ramda?

使用 Ramda 对数字进行排序很容易。

const sizes = ["18", "20", "16", "14"]
console.log("Sorted sizes", R.sort((a, b) => a - b, sizes))
//=> [ '14', '16', '18', '20' ]

使用原版 javascript 对单词数组进行排序也是如此。

const trees = ["cedar", "elm", "willow", "beech"]
console.log("Sorted trees", trees.sort())

你会如何使用 Ramda 对单词数组进行排序。
如果你不得不这样做。

const trees = ["cedar", "elm", "willow", "beech"]
console.log("Sorted trees", R.sort((a, b) => a - b, trees))
//=> ["cedar", "elm", "willow", "beech"]

不要尝试 减去 字符串 - 相反,请使用 localeCompare 检查一个字符串是否按字母顺序排在另一个字符串之前:

const trees = ["cedar", "elm", "willow", "beech"]
console.log("Sorted trees", R.sort((a, b) => a.localeCompare(b), trees))
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.js"></script>

这就是你用 Ramda 对单词数组进行排序的意思吗?

import R from 'ramda'
var objs = [ 
    { first_name: 'x', last_name: 'a'     },
    { first_name: 'y',    last_name: 'b'   },
    { first_name: 'z', last_name: 'c' }
];
var ascendingSortedObjs = R.sortBy(R.prop('last_nom'), objs)
var descendingSortedObjs = R.reverse(ascendingSortedObjs)

您可以使用 R.comparator and R.lt 创建一个比较器:

const trees = ["cedar", "elm", "willow", "beech"]
const result = R.sort(R.comparator(R.lt), trees)
console.log("Sorted trees", result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>

import R from 'ramda'

const names = ['Khan', 'Thanos', 'Hulk']

const sortNamesAsc = R.sortBy(R.identity) // alphabetically
const sortNamesDesc = R.pipe(sortNamesAsc, R.reverse)

sortNamesAsc(names) // ['Hulk', 'Khan', 'Thanos']
sortNamesDesc(names) // ['Thanos', 'Khan', 'Hulk']

Ramda Repl example