orderBy具有混合类型的列

时间:2016-07-14 13:19:25

标签: lodash

您能告诉如何使用orderBy来处理具有各种字段类型(字符串和数字)的对象吗? 例如

_.orderBy([{a: 3}, {a: 2}, {a: 'a'}, {a: 1}, {a: 'c'}, {a: 'b'}], ['a'], ['asc'])

我有

[{"a":2},{"a":3},{"a":"a"},{"a":1},{"a":"b"},{"a":"c"}]

但我怎么能得到像

这样的东西
[{"a":1},{"a":2},{"a":3},{"a":"a"},{"a":"b"},{"a":"c"}]

1 个答案:

答案 0 :(得分:0)

比较值的_.toString结果。

var input = [{a: 3}, {a: 2}, {a: 'a'}, {a: 1}, {a: 'c'}, {a: 'b'}],
    output = _.sortBy(input, o => _.toString(o['a']));

console.log(output);
<script src="https://cdn.jsdelivr.net/lodash/4.13.1/lodash.min.js"></script>

如果要先根据类型进行分区,请使用_.groupBy然后排序。

var input = [{a: 3}, {a: 2}, {a: 'a'}, {a: 1}, {a: 'c'}, {a: 'b'}];
    
var output = _(input)
    .groupBy(o => typeof o['a'])
    .map(a => _.sortBy(a, 'a'))
    .flatten()
    .value();

console.log(output);
<script src="https://cdn.jsdelivr.net/lodash/4.13.1/lodash.min.js"></script>