This post will discuss how to find the difference between two arrays in JavaScript. The solution should return an array containing all the elements of the first array which are not present in the second array.

For example, the difference between arrays [1,2,3,4] and [3,4,5] is [1,2].

1. Using Array.prototype.filter() function

You can use the filter() method to find the elements of the first array which are not in the second array. This filtering can be done using the:

a) indexOf() method

Download  Run Code

b). ES7 includes() method

Download  Run Code

c). ES6 Set Object

Download  Run Code

2. Using jQuery

With jQuery, you can use the .not() method to get the difference. To get the items of the first array which doesn’t exist in the second array, use the following code:

Download Code

 
Alternatively, you can use the grep() method, which works similarly to the JavaScript filter() method. The following example demonstrates its usage by removing items from the first array, which fails the specified condition.

Download Code

3. Using Underscore/Lodash Library

The Underscore and Lodash Library provides their implementation of the difference method _.difference, which returns values from an array that are not included in the other array.

Download Code

That’s all about finding the difference between two arrays in JavaScript.