0

I am new to typescript, and i want find a right way to solve my problem. So i have two arrays A and B, i need to find a difference between two arrays relative to array A and return a result in separate arrays what was addArray and what was removedArray For example:

A = [1, 2, 3, 4];
B = [1, 5, 6, 7];
addArray =[5,6,7]
removedArray =[2,3,4]

Looking for fast and elegant way

Happy Coder
  • 1,293
  • 1
  • 19
  • 35

1 Answers1

2

const A = [1, 2, 3, 4];
const B = [1, 5, 6, 7];
const difference = (left, right) => {
  let a = new Set(left);
  let b = new Set(right);
  return [...a].filter(x => !b.has(x))
}
const addArray = difference(B, A);
const removedArray = difference(A, B);

console.log({ addArray, removedArray });

References:

Doug Coburn
  • 2,485
  • 27
  • 24
  • Thank you! I am not agree with someone who set that question as duplicate..good to know that javascript supports sets – Happy Coder Mar 20 '19 at 00:58