Example 1: 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()})
}
})
})
Example 2: javascript check if two arrays of objects have same elements
var isEqual = function (value, other) {
var type = Object.prototype.toString.call(value);
if (type !== Object.prototype.toString.call(other)) return false;
if (['[object Array]', '[object Object]'].indexOf(type) < 0) return false;
var valueLen = type === '[object Array]' ? value.length : Object.keys(value).length;
var otherLen = type === '[object Array]' ? other.length : Object.keys(other).length;
if (valueLen !== otherLen) return false;
var compare = function (item1, item2) {
var itemType = Object.prototype.toString.call(item1);
if (['[object Array]', '[object Object]'].indexOf(itemType) >= 0) {
if (!isEqual(item1, item2)) return false;
}
else {
if (itemType !== Object.prototype.toString.call(item2)) return false;
if (itemType === '[object Function]') {
if (item1.toString() !== item2.toString()) return false;
} else {
if (item1 !== item2) return false;
}
}
};
if (type === '[object Array]') {
for (var i = 0; i < valueLen; i++) {
if (compare(value[i], other[i]) === false) return false;
}
} else {
for (var key in value) {
if (value.hasOwnProperty(key)) {
if (compare(value[key], other[key]) === false) return false;
}
}
}
return true;
};