Reputation: 1171
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"]
Upvotes: 6
Views: 11363
Reputation: 516
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']
Upvotes: 9
Reputation: 191986
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>
Upvotes: 11
Reputation:
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)
Upvotes: 0
Reputation: 370789
Don'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>
Upvotes: 15