I have 2 arrays:
blockedNumbers: ['123', '456', '789', '247'];
contacts: [
{name: 'Foo', numbers: [{ home:'123' }, { mobile:'456' }]},
{name: 'Bar', numbers: [{ home:'789' }]}
]
I want to create a new array of blocked contacts which will contain:
[
{ name: Foo, numbers: [{ home:'123' }, { mobile:'456' }] },
{name: 'Bar', numbers: [{ home:'789' }]}
'247'
]
So the solution I have tried first loops over blocked numbers, then forEach contact, if blocked number in numbers, push to array. But the result turns out as
[
'123'
{ name: Foo, numbers: ['123', '456'] },
{name: 'Bar', numbers: ['789']}
'456'
'789'
'247'
]
Code below:
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);
}
});
});
});
I'm sure there is a more efficient way to do this & actually return what I need? (All of the blacklisted contacts and if not in contacts, only the number) I am using js and React.js in this project