1

I wrote the function to accomplish what was asked, but was wondering if there was a better and nicer way to do that?

function arrayDiff(a, b) {
  let myArr = [];
  for (let i = 0; i < a.length; i++) {
    if (a[i] == b[0] || a[i] == b[1]) {
      continue;
    } else {
      myArr.push(a[i]);
    }
  }
  return myArr;
}
arrayDiff([1,2,3], [2,3]) //returns [1]

What if the length of the array "b" was more than just two elements, for example 5, how could I write a better code?

3 Answers3

1

const a = [1,2,3], b = [2,3]
let result = a.filter(n=>!b.includes(n))
console.log(result)
holydragon
  • 6,158
  • 6
  • 39
  • 62
1

You could take a single comparison by using Array#includes.

function arrayDiff(a, b) {
    let myArr = [];

    for (let i = 0; i < a.length; i++) {
        if (b.includes(a[i])) continue;
        myArr.push(a[i]);
    }

    return myArr;
}

console.log(arrayDiff([1, 2, 3], [2, 3])); // [1]

Another faster approach takes an object with O(1) fo looking for the value of b, for example with a Set.

function arrayDiff(a, b) {
    let myArr = [],
        excluding = new Set(b);

    for (let i = 0; i < a.length; i++) {
        if (excluding.has(a[i])) continue;
        myArr.push(a[i]);
    }

    return myArr;
}

console.log(arrayDiff([1, 2, 3], [2, 3])); // [1]
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

You can loop the second array and get the index of the item from the first array. Then use splice to remove the item from first array

function arrayDiff(a, b) {
  let z = a;
  b.forEach((item) => {
    const getIndx = z.indexOf(item);
    if (getIndx !== -1) {
      z.splice(getIndx, 1)
    }
  });
  return z;
}
console.log(arrayDiff([1, 2, 3], [2, 3]))
brk
  • 48,835
  • 10
  • 56
  • 78