1

I have two arrays that I want to compare and push values that are not the same in both to a new array. Basically I'm trying to push values from arrayTwo that are not in arrayOne to a new array.

  var arrayOne = [[1,"121"], [2,"111"], [2,"321"], [3,"232"], [3,"213"], [4,"211"]],
  arrayTwo = [[4,"111"], [1,"131"], [3,"321"], [3,"232"], [3,"211"], [3,"213"], [1, "X1X"]];
  doNotMatch = []; 

I tried looping through the first two arrays comparing the values like below but this obviously isn't working:

 for ( var i = 0; i < arrayOne.length; i++ ) {
        for ( var e = 0; e < arrayTwo.length; e++ ) {
            if ( arrayOne[i] !== arrayTwo[e]) {
                doNotMatch.push(arrayTwo[e])
                } 
        }
    }
MMM Bacon
  • 71
  • 2
  • 2
  • 12
  • You only want to push the new array if they do not match to every element in the other array, not to any. – Bergi Mar 28 '15 at 18:07
  • So you want to get the unique elements? – David Thomas Mar 28 '15 at 18:07
  • This might help. http://stackoverflow.com/questions/7837456/comparing-two-arrays-in-javascript[1] – Popmedic Mar 28 '15 at 18:07
  • What do you mean two values that are not the same? Values at the same index that don't match? Values that exist only in one of the two arrays, but not both? Values from arrayOne that do not exist in arrayTwo? – Joel Anderson Mar 28 '15 at 18:08
  • DavidThomas Yes, I only want to get the unique elements. @Joel Anderson In my updated post containing new array information, i would like to push values from arrayTwo that are not in arrayOne to a new array. – MMM Bacon Mar 29 '15 at 05:49

1 Answers1

5
var arrayOne = ["dog", "cat", "hamster", "gerbil", "turtle"],
    arrayTwo = ["hamster", "turtle", "gerbil"],
    doNotMatch = []; 

for(var i=0;i<arrayOne.length;i++){
   if(arrayTwo.indexOf(arrayOne[i])==-1){doNotMatch.push(arrayOne[i]);}
}

//doNotMatch is now ["dog","cat"]
nicael
  • 18,550
  • 13
  • 57
  • 90
  • Hi nicael, thanks for the comment! Your example works, but I updated my array information in the post to closer resemble the information I'll be working with in a prod environment. Any idea on how to separate the uniques? – MMM Bacon Mar 29 '15 at 05:40
  • @mmm Still, my answer works for your updated question. – nicael Mar 29 '15 at 08:43
  • nicael, if i plug in the updated arrays and run your for loop, it's pushing all of the values of arrayOne to the doNotMatch array, not just the uniques. Any other ideas are appreciated. – MMM Bacon Mar 29 '15 at 14:22