简体   繁体   中英

Lodash orderBy Function Not Sorting Correctly

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM