使用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"]
答案 0 :(得分:6)
不要尝试减去字符串-而是使用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>
答案 1 :(得分:5)
您可以使用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>
答案 2 :(得分:2)
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']
答案 3 :(得分:0)
这是用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)