gpt4 book ai didi

javascript - 如何计算JS中的重复对象

转载 作者:行者123 更新时间:2023-12-01 16:17:25 25 4
gpt4 key购买 nike

我正在尝试为 JS 中的重复项添加计数。在下面的这种情况下,我完全是堆栈。我需要比较具有两个值 (x, y) 的对象,如果存在相同的 (x, y) 值,则在新对象上添加计数 1。

有什么方法可以将数据转换为如下所示的新数据吗?

const data = [
{id: 1, x: 1, y: 1},
{id: 2, x: 2, y: 2},
{id: 3, x: 1, y: 1},
]

const newData = [
{x: 1, y:1 ,count:2}
{x: 2, y:2 ,count:1}
]

最佳答案

使用.reduce()函数

const data = [
{id: 1, x: 1, y: 1},
{id: 2, x: 2, y: 2},
{id: 3, x: 1, y: 1},
]

const output = data.reduce((acc, curr) => {
curr.count = 1;
const exists = acc.find(o => o.x === curr.x && o.y === curr.y);

exists ? exists.count++ : acc.push(({ x, y, count } = curr));

return acc;
}, []);

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

关于javascript - 如何计算JS中的重复对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62425038/

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