Search code examples
javascriptarray-difference

Finding the symmetric difference between two arrays


I need to find any differences between two arrays in the elements and push said elements onto a new array that is then returned in the end. I have pulled a function from this website through searching that has the intended purpose of counting the number of times an element occurs in an array and returning that. First I have concatenated the two arrays together, then applied this function (modified it to fit my problem as well as I could). I then tried to push the elements that were different (didn't occur twice) to the new array. My code of course doesn't work and I am also new to Javascript, so please be easy on me.

Below is some code of what I have tried, which doesn't pass any tests:

function diffArray(arr1, arr2) {
  var newArr = [];

  let tempArr = arr1.concat(arr2);

  function countInArray(array, what) {
    var count = 0;
    for (var i = 0; i < array.length; i++) {
        if (array[i] === what) {
            count++;
        }
    }
    if (countInArray(tempArr, tempArr[i]) < 2) {
      newArr.push(tempArr[i]);
    } 
}


  return newArr;
}

If you provide any code please try to break it down for me so that I can understand better and learn.


Solution

  • To achieve expected result, use below option by making few changes to your code

    1. Return count for countInArray (currently it returns undefined)

    function countInArray(array, what) { var count = 0; for (var i = 0; i < array.length; i++) { if (array[i] === what) { count++; } } return count }

    1. Remove calling countInArray inside countInArray method
    2. Run For Loop for tempArr to compare with other each value of tempArr

    for (var j = 0; j < tempArr.length; j++) { if (countInArray(tempArr, tempArr[j]) < 2) { newArr.push(tempArr[j]); } }

    Working code :

    function diffArray(arr1, arr2) {
      let tempArr = arr1.concat(arr2);
      let newArr = [];
      function countInArray(array, what) {
        var count = 0;
        for (var i = 0; i < array.length; i++) {
            if (array[i] === what) {
                count++;
            }
        }
        return count
    }
      
        for (var j = 0; j < tempArr.length; j++) {
           if (countInArray(tempArr, tempArr[j]) < 2) {
             newArr.push(tempArr[j]);
           } 
        }
    
    
      return newArr;
    }
    
    
    let arr1 = ["diorite", "andesite", "grass", "dirt", "pink wool", "dead shrub"]
    let arr2 = ["diorite", "andesite", "grass", "dirt", "dead shrub"]
    console.log(diffArray(arr1, arr2))
    
    let arr3 = [1, "calf", 3, "piglet"]
    let arr4 =  [7, "filly"]
    console.log(diffArray(arr3, arr4))

    codepen - https://codepen.io/nagasai/pen/OYNdZX?editors=1010