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:
Set Object
The set object method can retrieve the difference between two specified arrays.
includes()
The includes() method finds out whether an array contains a specified element or not:
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.