我需要转换一个数组,如下所示:
["Cats", "Cats", "Dogs", "Dogs", "Dogs"]
以下形式:
[
{ x: "Cats", y: 35 },
{ x: "Dogs", y: 40 },
{ x: "Birds", y: 55 },
]
哪里y
表示数组中相同元素的个数。
最佳答案
强调使用基于 map 的高效、现代的方法,该方法也可以在副本中以类似的形式找到:
const getCounts = iterable => {
const counts = new Map();
for (const x of iterable) {
counts.set(x, (counts.get(x) ?? 0) + 1); // use || for ES6 compat
}
return counts;
};
Array.from(
getCounts(["Cats", "Cats", "Dogs", "Dogs", "Dogs"]),
([x, y]) => ({x, y})
)
关于javascript - 如何计算数组中相同项目的数量并将计数分配给对象中的特定键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60749934/