How to Get the Difference Between Two Arrays in JavaScript

There are a variety of JavaScript and jQuery methods that help you get the difference between two arrays. Let's discuss each of them.

You can use a single line of code using the filter method of JavaScript Array, which will output those elements of arr1 that are not found in arr2. It can be done in three ways.

indexOf()

The indexOf() method returns the first index a given element can be found at in the array or it will return -1 if it is not present:

Javascript arrays indexOf method
let arr1 = [1, 2, 3, 4, 5]; let arr2 = [5, 6, 7, 8]; let difference = arr1.filter(x => arr2.indexOf(x) === -1); console.log(difference);

Set Object

The set object method can retrieve the difference between two specified arrays.

Javascript arrays Set object
let arr1 = [1, 2, 3, 4, 5]; let arr2 = [5, 6, 7, 8]; let b = new Set(arr2); let difference = [...arr1].filter(x => !b.has(x)); console.log(difference);

includes()

The includes() method finds out whether an array contains a specified element or not:

Javascript arrays includes method
let arr1 = [1, 2, 3, 4, 5]; let arr2 = [5, 6, 7, 8]; let difference = arr1.filter(x => !arr2.includes(x)); console.log(difference);

jQuery Methods

You can also use jQuery to find the difference between arrays with the grep() method:

const { JSDOM } = require("jsdom");
const { window } = new JSDOM();
let $ = require("jquery")(window);
let arr1 = [1, 2, 3, 4, 5];
let arr2 = [5, 6, 7, 8];
let difference = $.grep(arr1, (item) => $.inArray(item, arr2) === -1);
console.log(difference);

Another method of jQuery — not() can also handle comparing:

const { JSDOM } = require("jsdom");
const { window } = new JSDOM();
let $ = require("jquery")(window);
let arr1 = [1, 2, 3, 4, 5];
let arr2 = [5, 6, 7, 8];
let difference = $(arr1).not(arr2).get();
console.log(difference);

The filter Method

The filter()method initializes a new array with all elements that pass the test implemented by the provided function. This method calls a provided callback function once for each element in the array and constructs a new array containing all the values for which callback returns a value is true. Array elements that don't pass the callback test are missed out and aren't included in the new array.