Explain Codes LogoExplain Codes Logo

How to get the difference between two arrays of objects in JavaScript

javascript
prompt-engineering
functions
callbacks
Anton ShumikhinbyAnton Shumikhin·Feb 18, 2025
TLDR

Ready for a quick jaunt? Let's find unique objects in two arrays. We'll use properties like id and mighty duo of filter and some:

const diff = (a1, a2, key) => a1.filter(o1 => !a2.some(o2 => o1[key] === o2[key])); // Example (Abracadabra! Let's conjure up some objects): const arr1 = [{ id: 1 }, { id: 2 }]; const arr2 = [{ id: 2 }, { id: 3 }]; console.log(diff(arr1, arr2, 'id')); // [{ id: 1 }] - Voila! You see it, don't you?

The arduous journey into deep comparisons

The Fast answer was an audacious trick, but alas dear friends, when objects juggle more properties, you must craft a custom comparer function. A bold knight that presents the sword of specificity in your equality comparisons:

function deepDiff(a1, a2, comparer) { return a1.filter(o1 => !a2.some(o2 => comparer(o1, o2))); } // A comparer to vanquish the dragon of equality, based on their properties const comparer = (obj1, obj2) => { return Object.keys(obj1).every( key => obj1[key] === obj2[key] ); }; // The royal proclamation of function usage: const arr1 = [{ id: 1, value: 'Apple' }, { id: 2, value: 'Orange' }]; const arr2 = [{ id: 2, value: 'Orange' }, { id: 3, value: 'Peach' }]; console.log(deepDiff(arr1, arr2, comparer)); // [{ id: 1, value: 'Apple' }] - Huzzah! We have emerged victorious!

Expanding your arsenal - Alternative solutions

Is time of the essence? Does a large dataset breathe down your neck? Fear not! An efficient method hastens to your aid:

function efficientDiff(a1, a2, key) { const set = new Set(a2.map(item => item[key])); return a1.filter(item => !set.has(item[key])); }

Discovering the lost artifacts - Symmetric difference

To discover precious artifacts that only belong to one array, combine diff(a1, a2, key) with diff(a2, a1, key). Behold, the Symmetric Difference!

const symDiff = (a1, a2, key) => [...diff(a1, a2, key), ...diff(a2, a1, key)];

Calling the mighty helpers - Using libraries

For those who dread the large or complex, the well-renowned lodash springs forth into battle:

// Entering the realm of lodash const _ = require('lodash'); // Conquering DIFFerences const diff = _.differenceWith(arr1, arr2, _.isEqual); console.log(diff); // Casting the spell of _.isEqual onto the objects.

Plunging into the abyss - Handling nested objects

For those brave who dare challenge the nest of objects, equipping a deep equality check may be your best bet. Prepare yourself, and alter your comparer function:

// The capability of the deep equal function is of legends const deepEqual = (obj1, obj2) => { // It possesses the power to recursively traverse the object properties // A keeper of time and omnipotent in its function, it halts for nothing // Beware, only true warriors might command its power. };