gpt4 book ai didi

javascript - 从数组数组中获取计数

转载 作者:数据小太阳 更新时间:2023-10-29 04:59:44 26 4
gpt4 key购买 nike

下面有一组数组。使用 ES6,我如何才能将每个值 GoodExcellentWow 计数到一个新数组中,例如 [{name:好,数:4} {name: Excellent, count: 5}, {name:Wow, count:2}] 动态风格。我正在尝试使用 Object.assign 但我无法“唯一”地计算出键的计数,相反,我需要使用一个数组,因为我试图在前端呈现它.我需要使用 reduce 吗?怎么办?

let k = 0
const stats = {}
const remarks = [
[{name: "Good"}],
[{name: "Good"}, {name: "Excellent"}],
[{name: "Good"}, {name: "Excellent"}, {name: "Wow"}],
[{name: "Good"}, {name: "Excellent"}, {name: "Wow"}],
[{name: "Excellent"}],
[{name: "Excellent"}]
]

remarks.forEach((arr) => {
arr.map((e) => {
Object.assign(stats, { [e.name]: k = k + 1 })
})
})

console.log(stats);

输出:

stats: {Good: 8, Excellent: 11, Wow: 9}

这是不正确的,而且我需要使用数组。

预期输出:

[{name: Good, count: 4} {name: Excellent, count: 5}, {name:Wow, count:2}]

最佳答案

展平数组数组并从对象开始减少它,例如:{ Good: 0, Excellent: 0, Wow: 0}

然后 .map 结果的 Object.entries 将其转换为数组:

const remarks = [
[{ name: "Good" }],
[{ name: "Good" }, { name: "Excellent" }],
[{ name: "Good" }, { name: "Excellent" }, { name: "Wow" }],
[{ name: "Good" }, { name: "Excellent" }, { name: "Wow" }],
[{ name: "Excellent" }],
[{ name: "Excellent" }]
];

const result = Object.entries(
remarks.flat().reduce(
(all, { name }) => {
all[name] += 1;
return all;
},
{ Good: 0, Excellent: 0, Wow: 0 }
)
).map(([name, count]) => ({ name, count }));

console.log(result);

关于javascript - 从数组数组中获取计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57615151/

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