6 kyu · reference

Array.diff

ArraysFundamentalsAlgorithms

Implement a function that computes the difference between two lists. The function should remove all occurrences of elements from the first list (a) that are present in the second list (b). The order of elements in the first list should be preserved in the result.

Examples

If a = [1, 2] and b = [1], the result should be [2].

If a = [1, 2, 2, 2, 3] and b = [2], the result should be [1, 3].

## NOTE: 

In C, assign return array length to pointer `*z`

Solutions

01-solution.jsView on GitHub ↗
function arrayDiff(a, b) {
  const res = [];
  a.forEach((item, i) => {
    if (!b.includes(item)) {
      res.push(item);
    }
  });

  return res;
}

function arrayDiff(a, b) {
  return a.reduce((res, item) => {
    if (!b.includes(item)) {
      res.push(item);
    }
    return res;
  }, []);
}

function arrayDiff(a, b) {
  return a.filter(e => !b.includes(e));
}