Lodash sortBy以随机顺序返回元素(未排序)

时间:2018-07-04 19:12:00

标签: javascript arrays node.js lodash

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()可以正常工作。我想念什么?

1 个答案:

答案 0 :(得分: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>