Hi Everyone having an issue with a lodash function with react. I am trying to order an array of strings. I am copying the code exactly from the documentation which i used in the playground there and works fine but when i try run it in my code i have the same issue which i had while using the sort array.
Grabbing my array and throwing it right into the orderBy function but it is not order it correctly.
I want the editionsCount to sort according to its value but it keeps ordering the numbers not based on their actual value.
For example 108 will be smaller than 23 because 2 is bigger than three.
Here is the code I am running the lodash function in
const stableSort = (array, comparator) => {
console.log(_.orderBy(array, ["editionsCount"], ["desc"]));
}
Here is a screenshot of my response
Thanks in advance:)
The value of editionsCount
is a string, and is sorted by lexical order.
The _.orderBy()
function also accepts a function as the iteratee. To order by numeric order, supply a function that converts a string to a number. I've used the unary +
operator.
const arr = [{"editionsCount":"1"},{"editionsCount":"2"},{"editionsCount":"10"},{"editionsCount":"20"}]
// sort by numeric order
const sortByNumericValue = _.orderBy(arr, o => +o.editionsCount, ["desc"])
console.log(sortByNumericValue)
// Sort by lexical order
const sortByLexicalOrder = _.orderBy(arr, o => o.editionsCount, ["desc"])
console.log(sortByLexicalOrder)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>