HiveBrain v1.2.0
Get Started
← Back to all entries
gotchajavascriptCritical

How to get the difference between two arrays in JavaScript?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
howarraysbetweenthedifferencetwojavascriptget

Problem

Is there a way to return the difference between two arrays in JavaScript?

For example:

var a1 = ['a', 'b'];
var a2 = ['a', 'b', 'c', 'd'];

// need ["c", "d"]

Solution

This answer was written in 2009, so it is a bit outdated, also it's rather educational for understanding the problem. Best solution I'd use today would be

let difference = arr1.filter(x => !arr2.includes(x));


(credits to other author here)

I assume you are comparing a normal array. If not, you need to change the for loop to a for .. in loop.



`function arr_diff (a1, a2) {

var a = [], diff = [];

for (var i = 0; i

Code Snippets

let difference = arr1.filter(x => !arr2.includes(x));

Context

Stack Overflow Q#1187518, score: 387

Revisions (0)

No revisions yet.