Skip to content

Instantly share code, notes, and snippets.

@crouch74
Last active August 29, 2015 14:22
Show Gist options
  • Save crouch74/6554ac17eb326e67f4d4 to your computer and use it in GitHub Desktop.
Save crouch74/6554ac17eb326e67f4d4 to your computer and use it in GitHub Desktop.
difference between two arrays using reduce and the result with the same order (stable)
function diff(arr1, arr2) {
if(arr1.length === 0){
return arr2;
}
if(arr2.length === 0){
return arr1;
}
var newArr = [];
var deletedArr = [];
newArr = arr1.concat(arr2);
return newArr.reduceRight(function(c,l,index){
var index_l = newArr.indexOf(l);
if( index_l !== index || deletedArr.indexOf(l) > -1){
deletedArr.push(l);
}else{
c.push(l);
}
return c;
},[]).sort(function(a,b){
return newArr.indexOf(a) - newArr.indexOf(b);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment