How to Get the Difference Between Two Arrays in JavaScript

Arrays are a crucial data structure in JavaScript, and sometimes you may need to compare two arrays and get the difference between them.

In this Javascript tutorial, we will discuss different methods to get the difference between two arrays in JavaScript.

Arrays in JavaScript are used to store multiple values in a single variable.

They are dynamic, which means that you can add or remove elements from them at any time.

However, there may be instances where you need to compare two arrays and get the values that are unique to each of them.


Using the JavaScript Spread Operator and the Array.filter() Method

The spread operator in JavaScript allows you to spread elements of an array into a new array.

This makes it easy to compare two arrays and get the difference between them.

The Array.filter() method is used to filter the elements of an array based on a certain condition.

let array1 = [1, 2, 3, 4];
let array2 = [3, 4, 5, 6];
let difference = [...array1, ...array2].filter(
  item => !array1.includes(item) || !array2.includes(item)
);
console.log(difference);

Output:

[1, 2, 5, 6]

Using the JavaScript Array.reduce() Method

The Array.reduce() method is used to reduce an array to a single value by iterating through the array and applying a callback function to each element.

In this case, the callback function checks if the element is present in either array and adds it to a new array if it’s not.

let array1 = [1, 2, 3, 4];
let array2 = [3, 4, 5, 6];
let difference = array1.concat(array2).reduce((acc, current) => {
  if (!acc.includes(current)) {
    acc.push(current);
  }
  return acc;
}, []);
console.log(difference);

Output:

[1, 2, 3, 4, 5, 6]

Using the JavaScript Array.filter() Method

With a For Loop This method uses the Array.filter() method along with a for loop to compare two arrays and get the difference between them.

The for loop is used to iterate through each element in the first array, and the Array.filter() method is used to check if the element is present in the second array.

let array1 = [1, 2, 3, 4];
let array2 = [3, 4, 5, 6];
let difference = array1.filter(item => !array2.includes(item));
console.log(difference);

Output:

[1, 2]

Conclusion

In conclusion, there are several methods to get the difference between two arrays in JavaScript.

Each of these methods has its advantages and disadvantages, and the method you choose will depend on your specific use case.

Whether you’re using the spread operator and the Array.filter() method, the Array.reduce() method, or the Array.filter() method with a for loop, the important thing is that you understand how to get the difference between two arrays in JavaScript.