Last active
August 29, 2015 14:22
-
-
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)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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