Sorting numbers is easy with Ramda.
const sizes = ["18", "20", "16", "14"]
console.log("Sorted sizes", R.sort((a, b) => a - b, sizes))
//=> [ '14', '16', '18', '20' ]
Sorting an array of words with vanilla javascript is too.
const trees = ["cedar", "elm", "willow", "beech"]
console.log("Sorted trees", trees.sort())
How would you sort an array of words with Ramda.
If you had to.
const trees = ["cedar", "elm", "willow", "beech"]
console.log("Sorted trees", R.sort((a, b) => a - b, trees))
//=> ["cedar", "elm", "willow", "beech"]
Sorting numbers is easy with Ramda.
const sizes = ["18", "20", "16", "14"]
console.log("Sorted sizes", R.sort((a, b) => a - b, sizes))
//=> [ '14', '16', '18', '20' ]
Sorting an array of words with vanilla javascript is too.
const trees = ["cedar", "elm", "willow", "beech"]
console.log("Sorted trees", trees.sort())
How would you sort an array of words with Ramda.
If you had to.
const trees = ["cedar", "elm", "willow", "beech"]
console.log("Sorted trees", R.sort((a, b) => a - b, trees))
//=> ["cedar", "elm", "willow", "beech"]
Share
Improve this question
asked Sep 30, 2018 at 19:24
SifnosSifnos
1,1712 gold badges13 silver badges22 bronze badges
3
|
4 Answers
Reset to default 15Don't try to subtract strings - instead, use localeCompare
to check whether one string comes before another alphabetically:
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>
You can create a comparator with 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
Is this what you mean by sort an array of words with 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.sort
– CertainPerformance Commented Sep 30, 2018 at 19:29