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

Seb*_*che 1 javascript functional-programming ramda.js

使用Ramda可以轻松地对数字进行排序。

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

也可以使用香草javascript对单词数组进行排序。

const trees = ["cedar", "elm", "willow", "beech"]
console.log("Sorted trees", trees.sort())
Run Code Online (Sandbox Code Playgroud)

您如何用Ramda对单词数组进行排序。
如果必须的话。

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

Cer*_*nce 8

不要尝试减去字符串-而是使用localeCompare字母顺序检查一个字符串是否位于另一个字符串之前:

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


Ori*_*ori 6

您可以使用R.comparator和创建比较器R.lt

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


Han*_*and 6

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']
Run Code Online (Sandbox Code Playgroud)

Ramda Repl 示例