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"]
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.
To sort an array of strings in Java, we can use Arrays. sort() function.
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 ).
ES6 - Array Method sort() sort() method sorts the elements of an array.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With