Lodash orderBy对象数组的对象

时间:2017-10-19 17:59:27

标签: javascript lodash

我有一个数组:

const names = [{name: 'a', equal: 3},
{name: 'b', equal: 2},
{name: 'c', equal: 2},
{name: 'd', equal: 3},
{name: 'a1', equal: 1}]

我正在运行_.groupBy(名字,'相等'),结果我得到了:

{1: [{equal: 1, name: 'a1'}],
 2: [{equal: 2, name: 'b'}, {equal: 2, name: 'c'}],
 3: [{equal: 3, name: 'a'}, {equal: 3, name: 'd'}]}

但是这里按姓名排序消失了。如何在此对象中按名称排序?

更新

我想得到:

{3: [{equal: 3, name: 'a'}, {equal: 3, name: 'd'}],
 1: [{equal: 1, name: 'a1'}],
 2: [{equal: 2, name: 'b'}, {equal: 2, name: 'c'}]}

2 个答案:

答案 0 :(得分:1)

您可以将lodash方法groupBy和sortBy一起使用

<强>样本

const names = [{name: 'a', equal: 3},
{name: 'b', equal: 2},
{name: 'c', equal: 2},
{name: 'd', equal: 3},
{name: 'a1', equal: 1}];

var grouped = _.groupBy(names, function(name) {
  return name.equal;
});
 var result = _.sortBy(grouped, ['name']);
console.log(grouped);
<script src='https://cdn.jsdelivr.net/lodash/4.17.2/lodash.min.js'></script>

答案 1 :(得分:1)

通过将数组用作结果集,您可以在分组后对其进行排序。

var names = [{ name: 'a', equal: 3 }, { name: 'b', equal: 2 }, { name: 'c', equal: 2 }, { name: 'd', equal: 3 }, { name: 'a1', equal: 1 }],
    equals = {},
    result = [];

names.forEach(function (o) {
    if (!equals[o.equal]) {
        equals[o.equal] = [];
        result.push(equals[o.equal]);
    }
    equals[o.equal].push(o);
});

result.sort(function (a, b) {
    return a[0].name.localeCompare(b[0].name);
});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }