Trying to understand why I am getting the result that I am getting

Tell us what’s happening:
Describe your issue in detail here.
I have solved it already and trying to revisit it back again but I can’t figure out why this solution keeps adding duplicates of the missing item. trying to figure out a way to get around it.

I already know how to solve it using different methods, I am just trying to understand this one more
Your code so far


function diffArray(arr1, arr2) {
const newArr = [];
let longestArr= []
let shortArr=[];

if(arr1.length > arr2.length){
   longestArr = arr1
  shortArr= arr2
} else if (arr2.length > arr1.length){
   longestArr = arr2
      shortArr= arr1
} else {
  longestArr = arr1
      shortArr= arr2

}


// const items = longestArr.map(elem)
for(let i=0; i< longestArr.length; i++){
  let results = shortArr.filter(elem => {
if (shortArr.indexOf(longestArr[i]) === -1) {
  newArr.push(longestArr[i])
  console.log(newArr)
}
  })
 
} 


}

diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]);
  **Your browser information:**

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.84 Safari/537.36

Challenge: Diff Two Arrays

Link to the challenge:

Another question as well for a concept that i am not fully understanding
I looked at the solution utilizing the concat/filter/includes and wrote my version of it without copying but it’s also not working
I guess the problem I have here have to do with the solution using the return keyword,
However my approach was to to use more variables instead of chaining .
working solution from FCC:

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

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

and mine is

function diffArray(arr1, arr2) {
  const newArr = [];
  let res = arr1.concat(arr2)
let ay = res.filter(item => !arr1.includes(item)|| arr2.includes(item))
  return newArr;
}

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

appreciate your help understanding what’s going on here

You’ve got a few issues here:

let ay = res.filter(item => !arr1.includes(item)|| arr2.includes(item))

You are defining a new variable ay but then you never use is.

!arr1.includes(item)|| arr2.includes(item)

This logic isn’t quite right. I think you are missing something!!!

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.