Sym Diff between array challenge only works for all with inelegant fix

Sym Diff between array challenge only works for all with inelegant fix
0

#1

This worked except for when arr1 was empty I dont undestand why, I put a fix to make it work but its not a proffesional solution to a problem. Does anyone know why an empty array wont work without this first if statment I added?

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

if(arr1.length===0) {

      return arr2;   // This just accounts for when the first array is empty.
    } 

for(i=0;i<arr1.length;i++) { // This on its own does not work when arr1 is empty.
for(j=0;j<arr2.length;j++) {

    if (!arr2.includes(arr1[i])) {
      newArr.push(arr1[i]);
      }
    if (!arr1.includes(arr2[j])) {
     newArr.push(arr2[j]);
          
   }
 }

}

return newArr;
}

diffArray([], [“snuffleupagus”, “cookie monster”, “elmo”]); // This does not work without the first if statement as a fix.


#2

You have two nested for loops. If first array is empty, conditions for running first loop are never met, so it doesn’t run. And since the second loop is inside first, it doesn’t run too.


#3

There’s nothing wrong with an early exit condition. If you don’t like having two return statements, change return arr2; to newArr = [];

In terms of why you need that if statement, it’s because otherwise you never push anything to newArr.


for(i=0;i<arr1.length;i++) When arr1 is empty, arr1.length is 0. Because i is then equal to arr1.length, the code inside the for loop never runs and newArr is still it’s initial value when you return it.

You can make sure that the content of the loop runs at least once by using a do…while statement


I have applied that solution here

function diffArray(arr1, arr2) {
var newArr = [];
var i = 0;
do {
  for(j=0;j<arr2.length;j++) {

    if (arr1[i] && !arr2.includes(arr1[i])) { // note that I made a change this condition because arr1[i] will be undefined
      newArr.push(arr1[i]);
      }
    if (!arr1.includes(arr2[j])) {
     newArr.push(arr2[j]);

   }
 }
 i++;
}
while (i < arr1.length);

return newArr;
}

diffArray([], ["snuffleupagus", "cookie monster", "elmo"]); 

I don’t believe that either this solution nor the one you shared will actually pass the challenge, but I think I’ve duplicated your logic without the initial if.


#4

Ahhhh of course! The length of the array is 0! Thank you very much for your answer.