Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you sort an array of words with Ramda?

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"]
like image 875
Sifnos Avatar asked Sep 30 '18 19:09

Sifnos


People also ask

How do I sort the contents of an array?

Arrays.sort() works for arrays which can be of primitive data type also. Collections.sort() works for objects Collections like ArrayList, LinkedList, etc. Using the reverse order method: This method will sort the array in the descending.

How do you sort an array by string?

To sort an array of strings in Java, we can use Arrays. sort() function.

Is ramda better than Lodash?

Ramda is generally a better approach for functional programming as it was designed for this and has a community established in this sense. Lodash is generally better otherwise when needing specific functions (esp. debounce ).

How do I sort an array in ES6?

ES6 - Array Method sort() sort() method sorts the elements of an array.


1 Answers

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>
like image 177
CertainPerformance Avatar answered Sep 28 '22 07:09

CertainPerformance