Exercise 9: Find Difference Between Two Arrays

Problem Statement

Create a function `difference(arr1, arr2)` that returns elements from arr1 that are not in arr2. Example: difference([1, 2, 3], [2, 3, 4]) → [1]

Sample Output:

difference([1, 2, 3], [2, 3, 4]) => [1]
difference([1, 2, 3], [1]) => [2, 3]

Solution

const difference = (arr1, arr2) => {
  const set2 = new Set(arr2);
  return arr1.filter(x => !set2.has(x));
};

Explanation

Overall Goal:

  • Dono arrays me difference find karna.

Real world:

  • Data comparison: removed items find.
  • Set operations: difference operation.