Find which single item is missing from an array (comparing 2 arrays)

PHOTO EMBED

Mon Dec 21 2020 13:49:38 GMT+0000 (UTC)

Saved by @narro #javascript

// Example Arrays
let filterArrayB = ['aa', 'ab', 'ac', 'ad', 'ae', 'af', 'ag']
let filterArrayA = ['aa', 'ab', 'ac', 'ae', 'af', 'ag']

// This only works if there is a 1 item difference 
compare = (a,b) => {
  let inBoth = []
  let missingItem = []
  a.forEach(item => {
    for (let i=0; i<b.length; i++){
      if (item == b[i]){
        inBoth.push(item) 
        if (i == b.length) return
      } 
      if (a.length < b.length) {
        b.forEach(item => {
          if (!a.includes(item)){
            missingItem = item
          }
        })
      } else {
          a.forEach(item => {
          if (!b.includes(item)){
            missingItem = item
          }
        })
      }
      
    }
  })
  return missingItem
}

compare(filterArrayA, filterArrayB)
content_copyCOPY

Solution to an online code challenge