6

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"]
Sifnos
  • 1,161
  • 2
  • 13
  • 22

4 Answers4

15

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>
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
11

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>
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
9
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

0

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)