gpt4 book ai didi

javascript - 如何从对象数组中提取多属性重复项?

转载 作者:行者123 更新时间:2023-12-03 06:08:42 26 4
gpt4 key购买 nike

我有一个对象数组,其中属性可能共享相同的值:

const arr = [
{name: 'Stephan', phone: 123},
{name: 'Stephan', phone: 432},
{name: 'Begal', phone: 432},
{name: 'Lucy', phone: 777},
{name: 'Angel', phone: 432},
{name: 'Lucy', phone: 555},
{name: 'Mike', phone: 999},
];

(您可以观察到姓名或电话可以重复多次)。

我需要在单独的数组/对象中提取具有重复电话/姓名的对象以进行进一步操作。

理想情况下,从上面的示例生成的重复数组可能如下所示:

const dups = [
[
{name: 'Stephan', phone: 123},
{name: 'Stephan', phone: 432},
{name: 'Begal', phone: 432},
{name: 'Angel', phone: 432},
],
[
{name: 'Lucy', phone: 777},
{name: 'Lucy', phone: 555},
]
];

如何实现这一目标?

我的算法知识不强,但我想按姓名和电话对原始数组进行排序将是第一步?

最佳答案

无需排序。迭代数组并维护两个辅助索引,表示“姓名/电话 X 在 Y 组中”:

const arr = [
{name: 'Stephan', phone: 123},
{name: 'Stephan', phone: 432},
{name: 'Begal', phone: 432},
{name: 'Lucy', phone: 777},
{name: 'Angel', phone: 432},
{name: 'Lucy', phone: 555},
{name: 'Mike', phone: 999},
];


var groups = [[]],
names = {},
phones = {};

for (var obj of arr) {
var g = names[obj.name] || phones[obj.phone];
if (!g)
groups[g = groups.length] = [];
groups[g].push(obj);
names[obj.name] = phones[obj.phone] = g;
}

console.log(groups.slice(1))

关于javascript - 如何从对象数组中提取多属性重复项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39419161/

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