How to Get the Difference Between Two Arrays in JavaScript
Read this tutorial and learn several JavaScript and jQuery methods that help you get the difference between two arrays easily. Choose the best one for you.
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 implemented in several 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
Set Object
The set object method can retrieve the difference between two specified arrays.
Javascript arrays Set object
includes()
The includes() method finds out whether an array contains a specified element or not:
Javascript arrays includes method
jQuery Methods
Note: The following jQuery examples use JSDOM to run in a Node.js environment. In a standard browser, jQuery is typically loaded via a <script> tag.
You can also use jQuery to find the difference between arrays with the grep() method:
Javascript JQuery arrays 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);The filter Method
The filter() method creates a new array containing all elements that pass the test implemented by the provided function. It is the core method used in the examples above to isolate unique values.