2

Im trying to retrieve the not included value in the second array, by using the following code:

function diffArray(arr1, arr2) {
  var newArr = [];
  for (let i of arr1) {
    if (arr2.includes(i)) {
      newArr.push(i)
    }
  }
  return newArr
}

console.log(
  diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5])
)

Is there any way I can use another method to do this. I tried indexOf but I don't want the index.

Thank you

adiga
  • 34,372
  • 9
  • 61
  • 83
Tiago Ruivo
  • 183
  • 1
  • 9

3 Answers3

4

You can use filter():

let arr1 = [1, 2, 3, 5];
let arr2 = [1, 2, 3, 4, 5];

let result = arr2.filter(a2 => !arr1.includes(a2));
console.log(result);
mickl
  • 48,568
  • 9
  • 60
  • 89
  • 1
    No real need for `every` - `includes` still works `arr1.filter(item => !arr2.includes(item))` – VLAZ Dec 16 '19 at 15:48
2
if (!arr2.includes(i)) {
     newArr.push(i)
   } 

! means not

You could always use else as well, but it's more lines of code:

if (arr2.includes(i)) {
     // newArr.push(i)
 }  else {
    newArr.push(i);
}
TKoL
  • 13,158
  • 3
  • 39
  • 73
0
const a1 = [1, 2, 3, 4, 5];
const a2 = [1, 2, 3, 5];

function diffArray(arr1, arr2) {
  const frequencies = arr1.concat(arr2).reduce((frequencies, number) => {
    const frequency = frequencies[number];
    frequencies[number] = frequency ? frequency + 1 : 1;
    return frequencies;
  }, {});

  return Object.keys(frequencies).filter(number => frequencies[number] === 1);
}
  • That's way to complex for me to wrap... But thanks for the effort! – Tiago Ruivo Dec 16 '19 at 16:02
  • 1
    You are looking for the numbers that appear only in one of the arrays. I merged the two arrays and created an object where the keys are the numbers and the values are the number of times they appear in the merged array. Then removed the ones that occur more than 1 time. I didn't want to use includes because it goes through the array everytime until it doesn't find what you are looking for. –  Dec 16 '19 at 16:09