0

I am trying to compare 2 arrays and return a new array with any items only found in one of the two given arrays. So here is what I got:

function diffArray(arr1, arr2) {
  var newArr = [];
  var max;
  var test;
  (arr1.length > arr2.length) ? (max = arr1, test = arr2) : (max = arr2, test = arr1);
  for (let i = 0; i < test.length; i++) {
    if (max.indexOf(test[i]) === -1) {
      newArr.push(test[i])
    }
  }
  return newArr;
}

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

However, when I run it, newArr returns an empty array. Can someone point out the error?

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
GhostRoboXt
  • 114
  • 1
  • 11

2 Answers2

0

function diffArray(arr1, arr2) {
  var newArr = [];
  let checkArr = [];
  for (const val of arr1) {
    checkArr[val] = 0
  }
  for (const val of arr2) {
    checkArr[val] = checkArr[val] !== undefined ? checkArr[val] + 1 : 0
  }
  for (const val of arr1) {
    if (checkArr[val] === 0) {
        newArr.push(val)
    }
  }
  for (const val of arr2) {
    if (checkArr[val] === 0) {
        newArr.push(val)
    }
  }
  return newArr;
}

console.log(diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]));
fro
  • 402
  • 3
  • 8
  • While is does solve one of the problems it doesn't solve the following cases: 1) Arrays are the same length and have different values. 2) the shorter array has values the longer one doesn't – W-B Jul 09 '20 at 19:26
  • Just added another solution. That will be better, I think – fro Jul 09 '20 at 19:35
0

The error is that you are only checking the values in one array. You have to check for if values in arr1 are in arr2 and if values of arr2 are in arr1.

note: I added extra values to the arrays for testing

function diffArray(arr1, arr2) {
    var newArr = [];
    arr1.forEach(element => {
        if(arr2.indexOf(element) === -1){
            newArr.push(element)
        }
    });

    arr2.forEach(element => {
        if(arr1.indexOf(element) === -1){
            newArr.push(element)
        }
    });
    return newArr
  }
  
  console.log(diffArray([1, 2, 3,6, 5,7], [1, 2, 3, 4,10,23,11,123, 5]));
  console.log(diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]));
W-B
  • 850
  • 5
  • 16
  • For a much better solution please see Luis Sieira's answer [here](https://stackoverflow.com/questions/1187518/how-to-get-the-difference-between-two-arrays-in-javascript) – W-B Jul 09 '20 at 19:41