Skip to content

Instantly share code, notes, and snippets.

@joelbarbosa
Last active November 7, 2018 04:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joelbarbosa/145280f7f2f43bcdf377da217189d558 to your computer and use it in GitHub Desktop.
Save joelbarbosa/145280f7f2f43bcdf377da217189d558 to your computer and use it in GitHub Desktop.
diff arrays Javascript
const arr1 = [1, 2, 3, 4, 5];
const arr2 = [0, 2, 4, 6, 10, 11];
const DIFF = [1, 3, 5, 0, 6, 10, 11];
function diffWithFor(arr1, arr2) {
const holderArr = [];
for(let i = 0; i < arr1.length; i++) {
if (arr2.indexOf(arr1[i]) === -1) {
holderArr.push(arr1[i]);
}
}
for(let j = 0; j < arr2.length; j++) {
if(arr1.indexOf(arr2[j]) === -1) {
holderArr.push(arr2[j]);
}
}
return holderArr;
}
const arrDiff1 = diffWithFor(arr1, arr2);
console.assert(JSON.stringify(arrDiff1) === JSON.stringify(DIFF), '#diffWithFor Show this if it is not equal to');
function diffWithFilter(arr1, arr2) {
const tempArr1 = arr1.filter(item => arr2.indexOf(item) === -1);
const tempArr2 = arr2.filter(item => arr1.indexOf(item) === -1);
const holderArr = tempArr1.concat(tempArr2);
return holderArr;
}
const arrDiff2 = diffWithFilter(arr1, arr2);
console.assert(JSON.stringify(arrDiff2) === JSON.stringify(DIFF), '#diffWithFilter Show this if it is not equal to');
// console.log(arrDiff2)
function diffWithFilterAlternative(arr1, arr2) {
return arr1.filter(item => arr2.indexOf(item) === -1)
.concat(arr2.filter(item => arr1.indexOf(item) === -1));
}
const arrDiff3 = diffWithFilterAlternative(arr1, arr2);
console.assert(JSON.stringify(arrDiff3) === JSON.stringify(DIFF), '#diffWithFilterAlternative Show this if it is not equal to');
// console.log(arrDiff3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment