【问题标题】:Lodash sortBy returns elements in random order (not sorted)Lodash sortBy 以随机顺序返回元素(未排序)
【发布时间】:2018-12-13 06:02:04
【问题描述】:

Lodash sortBy 对我不起作用:

const _ = require('lodash');
let array = [3, 'q', 'e', 'w', 4, 'w', 1, 3, 2];
let data = _(array).sortBy(x => x);
console.log(data.value());
console.log(array.sort());

输出

[ 3, 'e', 'q', 'w', 4, 'w', 1, 2, 3 ]
[ 1, 2, 3, 3, 4, 'e', 'q', 'w', 'w' ]

.sortBy() 的输出毫无意义。内置.sort() 按预期工作。我错过了什么?

【问题讨论】:

标签: javascript arrays node.js lodash


【解决方案1】:

您可以将项目转换为字符串以进行比较

let array = [{a:3}, {a:'q'}, {a:'e'}, {a:'w'}, {a:4}, {a:'w'}, {a:1}, {a:3}, {a:2}];
let data = _(array).sortBy(x => x.a.toString());
console.log(data);
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.10/lodash.min.js"></script>

【讨论】:

  • 我不能,因为在我的实际程序中,我排序的值是数组元素的属性。为了简单起见,我在这里使用了身份。
  • 您应该使用更详细的示例项目列表来更新您的问题
  • 这将使示例更加复杂,我也无法使用.sort() 进行比较。我的实际值接近array.map(x => { foo: x }),对应的排序是_(array).sortBy('foo')
猜你喜欢
  • 1970-01-01
  • 2012-11-19
  • 2019-02-01
  • 2010-11-10
  • 2017-12-07
  • 1970-01-01
  • 2015-05-05
  • 1970-01-01
  • 2011-03-28
相关资源
最近更新 更多