I have two arrays:
var arr = [
{ id: 2, username: 'bill'},
{ id: 3, username: 'ted' }];
var b = ["ted", "bill", "john"];
how can I get one array like this:
var finalArr = [{id: 2, username: 'bill'},{id:3, username: 'ted'}. {id:0, username: 'john'}]
If user from array b exist in arr array to add id and if not id to be 0.
I tried something like this, but not working
var arr = [{
id: 2,
username: 'bill'
},
{
id: 3,
username: 'ted'
}
];
var b = ["ted", "bill", "john"];
var finalArr = [];
function userExists(username) {
var a = arr.some(item => {
if (item.username === username) {
finalArr.push({
username,
id: item.id
})
} else {
finalArr.push({
username,
id: 0
})
}
})
}
b.forEach(el => {
userExists(el)
})
console.log(finalArr)
usernameand differentidwithin yourarr? If you're not willing to remove those duplicates, you might check out my answer below.