【发布时间】:2017-10-19 13:38:55
【问题描述】:
我有以下数组:
var array = [
{ idOne: 1, oneText: 'one', idTwo: 2, twoText: 'two' },
{ idOne: 1, oneText: 'one', idTwo: 2, twoText: 'two' },
{ idOne: 12, oneText: 'twelve', idTwo: 23, twoText: 'twentythree' },
{ idOne: 12, oneText: 'twelve', idTwo: 23, twoText: 'twentythree' },
{ idOne: 12, oneText: 'twelve', idTwo: 25, twoText: 'twentyfive' },
{ idOne: 16, oneText: 'sixteen', idTwo: 56, twoText: 'fiftysix' },
{ idOne: 16, oneText: 'sixteen', idTwo: 56, twoText: 'fiftysix' },
{ idOne: 16, oneText: 'sixteen', idTwo: 56, twoText: 'fiftysix' },
{ idOne: 16, oneText: 'sixteen', idTwo: 50, twoText: 'fifty' },
{ idOne: 16, oneText: 'sixteen', idTwo: 50, twoText: 'fifty' },
{ idOne: 18, oneText: 'eighteen', idTwo: 90, twoText: 'ninety' }
];
我正在尝试先按 idOne 对它们进行分组,然后按 idTwo 对它们进行分组,并计算找到它们的数量,然后对它们进行排序:
我目前有以下方法:
var result = _.chain(array)
.groupBy("idOne")
.map(function(idOne, idOneKey) {
return _.chain(idOne)
.groupBy("idTwo")
.map(function(idTwo, idTwoKey) {
return {
id: idOneKey + '-' + idTwoKey
}
})
.value();
})
.value();
但我想返回以下数组或对象,不确定哪个最好:
result = {
'one-two': 2,
'twelve-twentythree': 2,
'twelve-twentyfive': 1,
'sixteen-fiftysix': 3
...
}
它不必使用下划线或lodash,只要它有效。
【问题讨论】:
-
是否允许原生 JS 解决方案?
-
我在一个 react 应用程序中实现了这个,所以无论什么都有效......
-
您是否想要一个具有如下结构的对象:{[idOne]:{[idTwo]:{object}}}?本质上是映射到对象的地图?
-
我必须在图表中使用它,所以我以后无论如何都需要这样做。 2个键的每个组合都是标签,它们的每个长度都是值
标签: javascript arrays sorting lodash