【问题标题】:Lodash OrderBy Alphabetical [duplicate]Lodash Order按字母顺序[重复]
【发布时间】:2019-11-26 20:14:17
【问题描述】:

我试图理解为什么 lodash orderBy 函数对这些的排序不正确。 (我想在我的大脑中是错误的)。

const data = [
  {
    id: '1',
    name: 'FLUoxetine (FLUoxetine 20 mg oral capsule)'
  },
  {
    id: '2',
    name: 'ascorbic acid (Vitamin C 25 mg oral tablet, chewable)'
  }
];

const orderedData = _.orderBy(data, ["name"], ["asc"]);

console.log("DATA>>>>", orderedData);
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.15/lodash.min.js"></script>

以上代码正在退出

DATAZZZZ 
[Object, Object]
0: Object
id: "1"
name: "FLUoxetine (FLUoxetine 20 mg oral capsule)"
1: Object
id: "2"
name: "ascorbic acid (Vitamin C 25 mg oral tablet, chewable)"

当我认为它会像这样注销时

DATAZZZZ 
[Object, Object]
0: Object
id: "2"
name: "ascorbic acid (Vitamin C 25 mg oral tablet, chewable)"
1: Object
id: "1"
name: "FLUoxetine (FLUoxetine 20 mg oral capsule)"

谁能解释一下为什么?我假设它与前 3 个字母大写有关。我阅读了 lodash 文档,但我要么错过了一些东西,要么没有完全理解它。任何帮助都是极好的。谢谢!

【问题讨论】:

  • 不区分大小写。
  • 在 JS 图表中,大写字符在小写之前,所以 'a' < 'F' === false,但 'A' < 'F' === true。如果您不想更改对象,则需要使用自己的回调。

标签: javascript function lodash


【解决方案1】:

小写和大写字母有不同的代码,大写字母在小写之前。如果您想要不区分大小写的排序,您可以将格式化程序函数作为迭代对象传递给orderBy

const sortedData = _.orderBy(data, [data => data.name.toLowerCase()], ['asc']);
console.log(sortedData);

【讨论】:

  • 但是你指定了desc而不是asc,所以你会得到与OP相同的结果而不是他们预期的结果..
  • @MarkReed 我的错,修好了。
【解决方案2】:

这确实与大小写有关。我建议使用 vanilla sort 方法,您可以在其中制定“自己的”规则。此外,它在您的项目中少了一个库!请注意,这将对当前数组进行排序,而不是复制现有数组。

const data = [
  {
    id: '1',
    name: 'FLUoxetine (FLUoxetine 20 mg oral capsule)'
  },
  {
    id: '2',
    name: 'ascorbic acid (Vitamin C 25 mg oral tablet, chewable)'
  }
];

data.sort((a, b) => {
    const textA = a.name.toUpperCase();
    const textB = b.name.toUpperCase();
    return (textA < textB) ? -1 : (textA > textB) ? 1 : 0;
});

【讨论】:

    猜你喜欢
    • 2019-12-16
    • 2014-12-21
    • 1970-01-01
    • 1970-01-01
    • 2011-08-31
    • 2021-06-05
    • 2017-12-19
    • 2011-05-29
    • 1970-01-01
    相关资源
    最近更新 更多