DEV Community

Mohammed Awad
Mohammed Awad

Posted on

Diff form Two Arrays

DESCRIPTION:

Compare two arrays and return a new array with any items only found in one of the two given arrays, but not both. In other words, return the symmetric difference of the two arrays.

Examples

[1, 2, 3, 5], [1, 2, 3, 4, 5]
// should return [4].

[1, "calf", 3, "piglet"], [1, "calf", 3, 4]
// should return ["piglet", 4].
Enter fullscreen mode Exit fullscreen mode

My approach for solving this problem:

  • concat the 2 arrayes.
  • add every item into new obj
  • if it's unquie get vlaue of 1 and get 2 if it's not.
  • if not return sliced str with num length.
  • filter item with value of 1 then map the number.

My solution:

function diffArray(arr1, arr2) {
    let newArr = arr1.concat(arr2)
    let numObj = {}
    newArr.forEach((item)=>{
      numObj[item] = numObj[item] ? numObj[item] +1:1
    })

    return Object.keys(numObj)
    .filter((item)=>{
      return numObj[item] == 1
    })
    .map((num)=>{
      if(!isNaN(num)){
          return +num
      }
      return num
    })
  }

  diffArray([1, "calf", 3, "piglet"], [1, "calf", 3, 4]);
Enter fullscreen mode Exit fullscreen mode

freeCodeCamp approach for solving this problem:

  • concat the 2 arrays.
  • filter if item includes in arr1 or arr2 and return him.

freeCodeCamp solution:

function diffArray(arr1, arr2) {
  return arr1
  .concat(arr2)
  .filter(item => !arr1.includes(item) || !arr2.includes(item));
}

diffArray([1, "calf", 3, "piglet"], [1, "calf", 3, 4]);
Enter fullscreen mode Exit fullscreen mode

Any tips or edit are most welcome. share it with me on the comments. Thanks for being here!

Follow Muhmmad Awd on

If you have any questions or feedback, please feel free to contact me at

Top comments (1)

Collapse
 
xmohammedawad profile image
Mohammed Awad

Any tips or edit are most welcome. share it with me on the comments. Thanks for being here!