Example 1: javascript compare object arrays keep only entries not in both
var result = result1.filter(function (o1) {
return result2.some(function (o2) {
return o1.id === o2.id;
});
});
let result = result1.filter(o1 => result2.some(o2 => o1.id === o2.id));
let result = result1.filter(o1 => !result2.some(o2 => o1.id === o2.id));
Example 2: javascript compare two arrays of objects get same elements
var result = result1.filter(function (o1) {
return result2.some(function (o2) {
return o1.id === o2.id;
});
});
let result = result1.filter(o1 => result2.some(o2 => o1.id === o2.id));
Example 3: match ids from 2 arrays in javascript asynchronous programming
var result1 = [
{id:1, name:'Sandra', type:'user', username:'sandra'},
{id:2, name:'John', type:'admin', username:'johnny2'},
{id:3, name:'Peter', type:'user', username:'pete'},
{id:4, name:'Bobby', type:'user', username:'be_bob'}
];
var result2 = [
{id:2, name:'John', email:'[email protected]'},
{id:4, name:'Bobby', email:'[email protected]'}
];
var props = ['id', 'name'];
var result = result1.filter(function(o1){
return !result2.some(function(o2){
return o1.id === o2.id;
});
}).map(function(o){
return props.reduce(function(newo, name){
newo[name] = o[name];
return newo;
}, {});
});
document.body.innerHTML = '<pre>' + JSON.stringify(result, null, 4) +
'</pre>';
Example 4: comparing array of objects in javascript
const groupInserts = [ { groups: [ 'Chess', 'Science', 'German' ], name: 'Ian Smith' },
{ groups: [ 'Swimming' ], name: 'Jenny Smith' },
{ groups: [ 'Tennis' ], name: 'Susan Jones' },
{ groups: [ 'Coding', 'Science' ], name: 'Judy Davis' } ]
const nameAndIdsFromDB = [ { name: 'Parent_1', id: 1 },
{ name: 'Parent_2', id: 2 },
{ name: 'Ian Smith', id: 99 },
{ name: 'Jenny Smith', id: 100 },
{ name: 'Susan Jones', id: 101 },
{ name: 'Judy Davis', id: 102 } ]
const groupnameAndIdsFromDB = [ { name: 'Debugging', id: 1 },
{ name: 'React', id: 2 },
{ name: 'New record with no people', id: 3 },
{ name: 'New record with people', id: 4 },
{ name: 'Chess', id: 12 },
{ name: 'Science', id: 13 },
{ name: 'German', id: 14 },
{ name: 'Swimming', id: 15 },
{ name: 'Tennis', id: 16 },
{ name: 'Coding', id: 17 } ]
let groupNamesWithIds = [];
groupInserts.forEach(data => {
if (data.groups) {
data.groups.map(e => {
let obj = {};
obj.group = e;
obj.name = data.name
groupNamesWithIds.push(obj);
})
}
})
let addedMessageGroupIds = [];
groupNamesWithIds.forEach(data => {
groupnameAndIdsFromDB.map(e => {
if (e.name === data.group) {
addedMessageGroupIds.push({group: data.group, name: data.name, messages_individual_groups_id: e.id})
}
})
})
let addedContactIds = [];
addedMessageGroupIds.forEach(data => {
nameAndIdsFromDB.map(e => {
if (e.name === data.name) {
addedContactIds.push({messages_individual_groups_id: data.messages_individual_groups_id, contact_id: e.id, created_at: Date.now()})
}
})
})