This page looks best with JavaScript enabled

Find Difference Between Arrays in Javascript

 ·   ·  ☕ 1 min read

Use set and filter to find the difference between two arrays.

1
2
3
4
let fruits1 = ["apple", "orange", "grapes"];
let fruits2 = ["banana", "mango", "apple"];
let difFruits = [...new Set(fruits1)].filter((item) => !fruits2.includes(item));
console.log(difFruits); // [ 'orange', 'grapes' ]

Similarly if you want to find the elements common in both arrays, you could employ a slightly different strategy.

1
2
3
4
5
6
let fruits1 = ["apple", "orange", "grapes"];
let fruits2 = ["banana", "mango", "apple"];
let commonFruits = [...new Set(fruits1)].filter((item) =>
  fruits2.includes(item)
);
console.log(commonFruits); // [ 'apple' ]

Traditionally, you would have executed two loops to find differences between arrays. Something like -

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
let fruits1 = ["apple", "orange", "grapes"];
let fruits2 = ["banana", "mango", "apple"];

const difFruits = [];
for (fruitOne of fruits1) {
  let found = false;

  for (fruitTwo of fruits2) {
    if (fruitTwo == fruitOne) {
      found = true;
      break;
    }
  } // fruits2 loop
  if (!found) difFruits.push(fruitOne);
} // fruits1 loop
console.log(difFruits); // [ 'orange', 'grapes' ]

We live in exciting times for sure.

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things