Compare two arrays and return a new array with any items only found in one of the original arrays.


/ Published in: JavaScript
Save to your folder(s)

Compare two arrays and return a new array with any items only found in one of the original arrays.
ex.,
[1, "calf", 3, "piglet"], [1, "calf", 3, 4] should return ["piglet", 4].


Copy this code and paste it in your HTML
  1. function diff(arr1, arr2) {
  2. var newArr = [];
  3.  
  4. newArr = arr1.diff(arr2).concat(arr2.diff(arr1));
  5.  
  6. return newArr;
  7. }
  8.  
  9. Array.prototype.diff = function(a) {
  10. return this.filter(function(i) {return a.indexOf(i) < 0;});
  11. };
  12.  
  13. function isSame(val1, val2) {
  14. return val1 === val2;
  15. }
  16.  
  17. diff([1, "calf", 3, "piglet"], [1, "calf", 3, 4] );

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.