Posted By

rain15 on 01/16/16


Tagged


Versions (?)

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


 / Published in: JavaScript
 

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].

  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
Posted By: kikimann on August 2, 2019

Any expert who can explain me what is the meaning of newArr = arr1.diff(arr2).concat(arr2.diff(arr1)); this line?

You need to login to post a comment.