【问题标题】:Lodash orderBy Function Not Sorting CorrectlyLodash orderBy 函数未正确排序
【发布时间】:2020-05-16 03:07:14
【问题描述】:

大家好,大家对 lodash 函数的反应有疑问。我正在尝试订购一个字符串数组。我正在从我在操场上使用的文档中完全复制代码并且工作正常,但是当我尝试在我的代码中运行它时,我遇到了与使用排序数组时相同的问题。

抓取我的数组并将其直接扔到 orderBy 函数中,但它没有正确排序。

我希望 editionsCount 根据其值进行排序,但它不断地对数字进行排序,而不是根据它们的实际值。

例如 108 将小于 23,因为 2 大于 3。

这是我在

中运行 lodash 函数的代码
const stableSort = (array, comparator) => {
    console.log(_.orderBy(array, ["editionsCount"], ["desc"]));
  }

这是我的回复截图

提前致谢:)

【问题讨论】:

  • 这就是字符串的比较方式,按字典顺序。如果您想比较它们,就好像它们是数字一样,您需要将它们转换为数字
  • 可以在 orderBy 函数中这样做吗?

标签: javascript arrays lodash


【解决方案1】:

editionsCount 的值是一个字符串,按词法排序。

_.orderBy() 函数也接受一个函数作为迭代对象。要按数字顺序排序,请提供一个将字符串转换为数字的函数。我使用了unary + 运算符。

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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多