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

标签 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' ]

使用 vanilla 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>

关于javascript - 你如何使用 Ramda 对单词数组进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52581365/

相关文章:

functional-programming - 我可以在 Google 的 Native Client 中使用 Gambit-C、Mlton 或 Chicken Scheme 吗

javascript - 将自定义 Hook 注入(inject) evolve 函数的优雅方式

javascript - 测试对象数组中是否存在值

javascript - jquery 访问数据属性

javascript - Javascript 中的累积分布函数

javascript - 单击时将文本添加到输入

javascript - 左关联二叉树折叠

python - python表达式中的临时变量

javascript - 使用 lodash.groupBy() 标准化对象

php - 将 PHP session 数组值导入 Javascript