0

So this function should remove all values from list a, which are present in list b.
arrayDiff([1,2],[1]) == [2]
and
If a value is present in b, all of its occurrences must be removed from the other:
arrayDiff([1,2,2,2,3],[2]) == [1,3]

I've made a function, but with some arrays it works and with some don't, I can't figure out why.

function arrayDiff(a, b) {
  let arrayA = a;
  let arrayB = b;

  arrayA.map(x => {
    let similarV = arrayB.find(element => element == x); //Get value that is present in both arrays
    if (similarV !== undefined) { //Check if its defined value
      var indexes = [],
        i = -1; //Get all positions of x element in arrayA
      while ((i = arrayA.indexOf(similarV, i + 1)) != -1) {
        indexes.push(i);
      };
      for (var i = indexes.length - 1; i >= 0; i--) { //Delete all the elements from arrayA with indexes from variable - indexes
        arrayA.splice(indexes[i], 1);
      }
    }

  });
  return arrayA;
}

console.log("Result: " +arrayDiff([6,4,16,-15,5,16,-4,4,-3,8,18,7,5,-14,2,9,2],[4,-4,9]));
console.log("Expected: " + [6, 16, -15, 5, 16, -3, 8, 18, 7, 5, -14, 2, 2]);

console.log("Result: " +arrayDiff([-6,15,4,-20,-19,-5,-8,7],[-20,4,-8,-5,15,7]));
console.log("Expected: " + [-6, -19]);
Condomer
  • 39
  • 5

3 Answers3

0

You could use filter and includes easily.

return arr1.filter(x => !arr2.includes(x));
robinvrd
  • 1,390
  • 8
  • 25
0

With filter()

function arrayDiff(a, b) {
  let c = a.filter(i => !b.includes(i))
  let d = b.filter(i => !a.includes(i))
  return [...c, ...d]
}

console.log("Result: " + arrayDiff([6, 4, 16, -15, 5, 16, -4, 4, -3, 8, 18, 7, 5, -14, 2, 9, 2], [4, -4, 9]));
console.log("Expected: " + [6, 16, -15, 5, 16, -3, 8, 18, 7, 5, -14, 2, 2]);

console.log("Result: " + arrayDiff([-6, 15, 4, -20, -19, -5, -8, 7], [-20, 4, -8, -5, 15, 7]));
console.log("Expected: " + [-6, -19]);
0

use filter

function arrayDiff(arr1,arr2){
  return arr1.filter(x=>!arr2.some(y=>x==y))
  }
  console.log("Result: " +arrayDiff([6,4,16,-15,5,16,-4,4,-3,8,18,7,5,-14,2,9,2],[4,-4,9]));
Sven.hig
  • 4,315
  • 2
  • 5
  • 18