Explain Codes LogoExplain Codes Logo

How to get the difference between two arrays in JavaScript?

javascript
array-difference
filter
lodash
Anton ShumikhinbyAnton Shumikhin·Jul 22, 2024
TLDR

Here's the secret sauce to get the difference between two arrays using filter() and includes():

// Unique to array1 const uninvited = [1, 2, 3].filter(x => ![4, 5].includes(x)); // Party crashers: [1, 2, 3] // Unique to array2 const noShows = [4, 5].filter(x => ![1, 2, 3].includes(x)); // RSVPs who ghosted us: [4, 5] // Symmetric difference const talliedList = [...uninvited, ...noShows]; // Entire guest drama: [1, 2, 3, 4, 5]

This gives you the unique culprits and the full summary of guest drama, in a quick copy-paste snippet.

Building a magic diff method

Why not give the Array prototype a diff method for those recurring gigs?

Array.prototype.diff = function(arr) { return this.filter(el => !arr.includes(el)); // Shoo, party crashers! };

How to use it:

let arrivals = ['Alice', 'Bob', 'Dave']; let invitees = ['Alice', 'Eve']; let intruders = arrivals.diff(invitees); // ['Bob', 'Dave'] let ghosts = invitees.diff(arrivals); // ['Eve']

This clever method will keep your code clean and free of unwanted duplicates—a true ghost buster!

More power for big guest lists

Got a big bash to manage? Trade the filter()-includes() combo for object-based operations:

function arrayWithDifference(arr1, arr2) { let attendanceLog = {}; arr1.forEach(guest => attendanceLog[guest] = true); arr2.forEach(guest => attendanceLog[guest] ? delete attendanceLog[guest] : null); return Object.keys(attendanceLog); // And voila! The ghosts and gatecrashers. }

Object properties are your friends when it comes to looking things up quickly. Big party? No problem.

Leveraging third-party libraries

Already got Lodash or jQuery on the script tags? Tap into their pre-baked methods:

  • Lodash's _.difference(array, [values]) for those who love being declarative.
  • jQuery's $(array1).not(array2).get() for those who embrace the chain.

Why reinvent the wheel when these libraries got your back in the array difference game?

Dabbling with Venn diagrams

A Venn Diagram can light our way in set operations, with an array representing each circle. Our mission: Identify the non-overlapping sections and make an invite for the next party.

Diving deeper

Mustering the peculiarities of includes() and filter() methods is key to brave the quirks of JavaScript. My advice: lurk around MDN more often.