How to find the difference of values ​​in two-dimensional arrays?

arr1 = [[35,70],[433,70],[35,73],[433,73],[35,154],[433,154]] arr2 = [[433,70],[433,154],[433,73],[35,154],[1,2,3]] 

The result should be:

 res = [[35,70],[35,73]] 

My code is:

 var arr1 = [[35,70],[433,70],[35,73],[433,73],[35,154],[433,154]]; var arr2 = [[433,70],[433,154],[433,73],[35,154],[1,2,3]]; var res = []; for (var i = 0; i < arr2.length; i++) { res.push(arr1.splice(arr1.indexOf(arr2[i]), 1)); } console.log(res);//нужно [[35,70],[35,73]] 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script> 

  • How do you think Array.indexOf returns? - Igor
  • @Igor Position of values ​​in the array - Yevheniy Antikov
  • well, but all the elements in your arrays are different objects - Igor
  • that is, all your indexOf calls return -1 - Igor
  • @Igor How do you do then? I tried to translate the string JSON.stringify, but I still could not find the necessary elements - Yevheniy Antikov

3 answers 3

It's strange that you did not work with JSON.stringify

 arr1 = [[35,70],[433,70],[35,73],[433,73],[35,154],[433,154]] arr2 = [[433,70],[433,154],[433,73],[35,154],[1,2,3]] arr1 = arr1.map(function(x) { return JSON.stringify(x) }) arr2 = arr2.map(function(x) { return JSON.stringify(x) }) function diffTest(x) { for(var i=0; i < arr2.length; i++) { if (arr2[i] === x) return false; } return true; } diff = arr1.filter(diffTest).map(function(x) { return JSON.parse(x) }) // [ [ 35, 70 ], [ 35, 73 ] ] 

It is possible to compare arrays in a loop, without json

     var arr1 = [[35,70],[433,70],[35,73],[433,73],[35,154],[433,154]]; var arr2 = [[433,70],[433,154],[433,73],[35,154],[1,2,3]]; function AnotB(a, b) { var diff = [], elA, elB, i, j, found; loopA: for (i = 0; i < a.length; i++) { elA = a[i]; found = false; loopB: for (j = 0; j < b.length; j++) { elB = b[j]; if( elA.length !== elB.length) continue loopB; for( k = 0; k < elA.length; k++) { if( elA[k] !== elB[k]) continue loopB; } found = true; break loopB; } if(!found) diff.push(elA); } return diff; } AnotB(arr1, arr2); // [[35,70],[35,73]] 

      Thanks to everyone for the answers, I also made my own version:

       var arr1 = [[35,70],[433,70],[35,73],[433,73],[35,154],[433,154]] var arr2 = [[433,70],[433,154],[433,73],[35,154]] for (var i = 0; i < arr1.length; i++) { if(!isItemInArray(arr2,arr1[i])==true){ console.log(arr1[i]); } } function isItemInArray(array, item) { for (var i = 0; i < array.length; i++) { if (array[i][0] == item[0] && array[i][1] == item[1]) { return true; } } return false; } 
       <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>