javascript compare array of objects code example

Example 1: 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; // return the ones with equal id
   });
});
// if you want to be more clever...
let result = result1.filter(o1 => result2.some(o2 => o1.id === o2.id));

Example 2: best way compare arrays javascript

// To compare arrays (or any other object):
// Simple Array Example:
const array1 = ['potato', 'banana', 'soup']
const array2 = ['potato', 'orange', 'soup']

array1 === array2;
// Returns false due to referential equality
JSON.stringify(array1) === JSON.stringify(array2);
// Returns true 


// Another Example:
const deepArray1 = [{test: 'dummy'}, [['woo', 'ya'], 'weird']]
const deepArray2 = [{test: 'dummy'}, [['woo', 'ya'], 'weird']]

deepArray1 === deepArray2;
// Returns false due to referential equality
JSON.stringify(deepArray1) === JSON.stringify(deepArray2);
// Returns true

Example 3: comparing two array of objects in javascript returning differences

a = [{ value:"4a55eff3-1e0d-4a81-9105-3ddd7521d642", display:"Jamsheer"}, { value:"644838b3-604d-4899-8b78-09e4799f586f", display:"Muhammed"}, { value:"b6ee537a-375c-45bd-b9d4-4dd84a75041d", display:"Ravi"}, { value:"e97339e1-939d-47ab-974c-1b68c9cfb536", display:"Ajmal"},  { value:"a63a6f77-c637-454e-abf2-dfb9b543af6c", display:"Ryan"}]
b = [{ value:"4a55eff3-1e0d-4a81-9105-3ddd7521d642", display:"Jamsheer", $$hashKey:"008"}, { value:"644838b3-604d-4899-8b78-09e4799f586f", display:"Muhammed", $$hashKey:"009"}, { value:"b6ee537a-375c-45bd-b9d4-4dd84a75041d", display:"Ravi", $$hashKey:"00A"}, { value:"e97339e1-939d-47ab-974c-1b68c9cfb536", display:"Ajmal", $$hashKey:"00B"}]

function comparer(otherArray){
  return function(current){
    return otherArray.filter(function(other){
      return other.value == current.value && other.display == current.display
    }).length == 0;
  }
}

var onlyInA = a.filter(comparer(b));
var onlyInB = b.filter(comparer(a));

result = onlyInA.concat(onlyInB);

console.log(result);

Example 4: how to compare two arrays javascript

function arraysAreIdentical(arr1, arr2){
    if (arr1.length !== arr2.length) return false;
    for (var i = 0, len = arr1.length; i < len; i++){
        if (arr1[i] !== arr2[i]){
            return false;
        }
    }
    return true; 
}

Example 5: comparing array of objects in javascript

// IN THIS EXAMPLE WE HAVE GROUP INSERTS - DATA TO BE ADDED TO DB
// TO INSERT INTO DB EACH GROUP NAME MUST BE THE MATCHING ID
// CONATCT NAME MUST ALSO BE MATCHING ID
// THE CODE BELOW SHOWS HOW TO TRAVERSE THROGUH TWO ARRAYS AND COMPARE / ADD VALES

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 6: javascript check if two arrays of objects have same elements

var isEqual = function (value, other) {

	// Get the value type
	var type = Object.prototype.toString.call(value);

	// If the two objects are not the same type, return false
	if (type !== Object.prototype.toString.call(other)) return false;

	// If items are not an object or array, return false
	if (['[object Array]', '[object Object]'].indexOf(type) < 0) return false;

	// Compare the length of the length of the two items
	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;

	// Compare two items
	var compare = function (item1, item2) {

		// Get the object type
		var itemType = Object.prototype.toString.call(item1);

		// If an object or array, compare recursively
		if (['[object Array]', '[object Object]'].indexOf(itemType) >= 0) {
			if (!isEqual(item1, item2)) return false;
		}

		// Otherwise, do a simple comparison
		else {

			// If the two items are not the same type, return false
			if (itemType !== Object.prototype.toString.call(item2)) return false;

			// Else if it's a function, convert to a string and compare
			// Otherwise, just compare
			if (itemType === '[object Function]') {
				if (item1.toString() !== item2.toString()) return false;
			} else {
				if (item1 !== item2) return false;
			}

		}
	};

	// Compare properties
	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;
			}
		}
	}

	// If nothing failed, return true
	return true;

};