我有一个对象数组,其中属性可以共享相同的值:
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},
]
];
如何实现?
我的算法知识不强,但我想通过名称和手机对原始数组进行排序是第一步吗?
答案 0 :(得分:1)
无需排序。迭代数组并维护两个帮助索引,表示“名称/电话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))