gpt4 book ai didi

javascript - 数组按两次分组并计算出现次数

转载 作者:行者123 更新时间:2023-11-28 14:44:41 25 4
gpt4 key购买 nike

我有以下数组:

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
...
}

它不必带有下划线或破折号,只要它起作用即可。

最佳答案

您可以使用countBy而不是 groupBy:

let result = _.countBy(array, item => item.oneText + '-' + item.twoText);

关于javascript - 数组按两次分组并计算出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46831289/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com