Given two arrays, the task is to find the difference between two arrays in JavaScript. The difference between two arrays means the elements that are present in one array but not in the other. There are several methods to calculate these differences.
1. Using filter() Method
The filter()
method is one of the most efficient ways to compute the difference between two arrays. It creates a new array containing elements that pass a given condition.
Find elements in array1
that are not in array2
:
let arr1 = [10, 20, 30, 40, 50]; let arr2 = [40, 50, 60, 70, 80]; let diff = arr1.filter(item => !arr2.includes(item)); console.log(diff); // Output: [10, 20, 30]
2. Using Set for Improved Performance
The Set
object provides a fast way to check membership, making it an excellent choice for finding differences between arrays.
let arr1 = [10, 20, 30, 40, 50]; let arr2 = [40, 50, 60, 70, 80]; let set2 = new Set(arr2); let diff = arr1.filter(item => !set2.has(item)); console.log(diff); // Output: [10, 20, 30]
3. Using reduce() Method
The reduce()
method can accumulate a new array by selectively including elements that satisfy a condition.
let arr1 = [10, 20, 30, 40, 50]; let arr2 = [40, 50, 60, 70, 80]; let diff = arr1.reduce((acc, item) => { if (!arr2.includes(item)) { acc.push(item); } return acc; }, []); console.log(diff); // Output: [10, 20, 30]
4. Using Loops
Traditional for
or for...of
loops provide a straightforward way to compute the difference, especially in older JavaScript environments.
Example: Using a for
Loop
let arr1 = [10, 20, 30, 40, 50]; let arr2 = [40, 50, 60, 70, 80]; let diff = []; for (let i = 0; i < arr1.length; i++) { if (!arr2.includes(arr1[i])) { diff.push(arr1[i]); } } console.log(diff); // Output: [10, 20, 30]
Example: Using for...of
let arr1 = [10, 20, 30, 40, 50]; let arr2 = [40, 50, 60, 70, 80]; let diff = []; for (let item of arr1) { if (!arr2.includes(item)) { diff.push(item); } } console.log(diff); // Output: [10, 20, 30]
5. Using Lodash’s _.difference() Method
If you’re using Lodash, the _.difference()
method provides a simple way to find the difference between two arrays.
const _ = require('lodash'); let arr1 = [10, 20, 30, 40, 50]; let arr2 = [40, 50, 60, 70, 80]; let diff = _.difference(arr1, arr2); console.log(diff); // Output: [10, 20, 30]
6. Bidirectional Difference
Sometimes, you may need to calculate elements unique to both arrays (symmetric difference).
let arr1 = [10, 20, 30, 40, 50]; let arr2 = [40, 50, 60, 70, 80]; let set1 = new Set(arr1); let set2 = new Set(arr2); let diff = [ ...arr1.filter(item => !set2.has(item)), ...arr2.filter(item => !set1.has(item)) ]; console.log(diff); // Output: [10, 20, 30, 60, 70, 80]