gpt4 book ai didi

javascript - 比较 2 个对象数组中的值并创建新数组,js

转载 作者:行者123 更新时间:2023-11-29 17:43:19 25 4
gpt4 key购买 nike

我有 2 个数组:

blockedNumbers: ['123', '456', '789', '247'];
contacts: [
{name: 'Foo', numbers: [{ home:'123' }, { mobile:'456' }]},
{name: 'Bar', numbers: [{ home:'789' }]}
]

我想创建一个新的被阻止的联系人数组,其中将包含:

[
{ name: Foo, numbers: [{ home:'123' }, { mobile:'456' }] },
{name: 'Bar', numbers: [{ home:'789' }]}
'247'
]

所以我尝试过的解决方案首先循环遍历被阻止的号码,然后是 forEach 联系人,如果被阻止的号码在号码中,则推送到数组。但是结果却是

[
'123'
{ name: Foo, numbers: ['123', '456'] },
{name: 'Bar', numbers: ['789']}
'456'
'789'
'247'
]

代码如下:

const newBlacklistWithContacts = [];
blockedNumbers.forEach((blockedNumber) => {
contacts.map((contact) => {
// if blocked number in contacts
Object.keys(contact.numbers).forEach((e) => {
if (contact.numbers[e] === blockedNumber) {
const alreadyAdded = newBlacklistWithContacts.find(blacklistContact => blacklistContact.name === contact.name);
if (!alreadyAdded) {
return newBlacklistWithContacts.push({ name: contact.name, numbers: contact.numbers });
}
}
else if (!newBlacklistWithContacts.includes(blockedNumber)) {
return newBlacklistWithContacts.push(blockedNumber);
}
});
});
});

我确定有一种更有效的方法可以做到这一点并实际返回我需要的东西? (所有列入黑名单的联系人,如果不在联系人中,只有号码)我在这个项目中使用 js 和 React.js

最佳答案

如果您的数据集非常大,您可以通过在 Set 中执行 O(1) 查找而不是使用 indexOf 来优化您的算法> 或 includes 执行 O(n) 查找:

// Input
const blockedNumbers = ['123', '456', '789', '247'];
const contacts = [{name: 'Foo', numbers: [{ home:'123' }, { mobile:'456' }]}, {name: 'Bar', numbers: [{ home:'789' }]}];

// Algorithm
const set = new Set(blockedNumbers);
const notused = new Set(blockedNumbers);
const newBlacklistWithContacts = contacts.filter(contact =>
contact.numbers.map(obj => Object.values(obj)[0])
.filter(number => set.has(number) && (notused.delete(number) || true)).length
).concat(...notused);

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

关于javascript - 比较 2 个对象数组中的值并创建新数组,js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51726505/

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