[英]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' ]
使用 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>
您可以使用R.comparator
和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 对一系列单词进行排序的意思吗?
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.