What do you think of my 'Diff Two Arrays' Solution?

What do you think of my 'Diff Two Arrays' Solution?
0.0 0

#1

So i totally came up with this on my own, and I’m pretty proud of it :sunglasses:

The problem asks to compare two arrays and return an array that contains only the differences.

Can you let me know what you think of this? I’m feeling really motivated right now and wanted to share, I’m really sorry if I’m being annoying hahaha

Please let me know if there’s anything you don’t like about it too.

function diffArray(arr1, arr2) {
  var newArr = [];
  
  joinArr = arr1.concat(arr2);
        
  for(i=0;i<joinArr.length;i++){
    if(joinArr.indexOf(joinArr[i]) == joinArr.lastIndexOf(joinArr[i])){
      newArr.push(joinArr[i]);
    }
  }
  
  return newArr;
}

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

#2

You can replace that using filter ()

Good job :wink:


#3

Thanks Neckers, what kind of callback couid I use to replace it using filter()? I was toying around with the idea of using a count for each new element it comes across, but I don’t know of a way to do that. @NeckersBOX


#4

This looks good, There is a similar trick I found (prob stakcoverflow) and used in some of my projects:

if (arr.indexOf(name) == i)

They basically do the same thing, check to see if there is more than one copy.


#5

and then try something like this for filter (pseudocode, check syntax)

joinArr.filter(function(elem){
return (arr.indexOf(name) ==i)
});

I’ll let you create the filter using your function on your own.


#6

Thanks for the tip Adventure bear. The more I get into programming the more I realize there are a bunch of shortcuts out there. One thing I don’t understand is when people write something like if(variable) , when variable is just an array or a string or something like that. I don’t get how that is a condition.


#7

When you see if (variable) {some function} what you expect is that “variable” will evaluate to true or false. Typically I think of it as “if variable exists”. but in order to not get any surprises, you should check it by console.log(“Inside conditional function”).

I’m sure there are better ways to do this but if you read in the MDN (Mozilla Developers Network) and look specifically for what is returned from various methods, look for true or false cases to be returned.

Someone smarter than I should come along any secodn now and give better advice…


#8

Ah that makes sense, thanks. I will definitely have to read up on that some more.