Skip to content

Instantly share code, notes, and snippets.

@hoanbka
Created November 10, 2017 18:00
Show Gist options
  • Save hoanbka/e0a777b877cad07b61b7595811de2538 to your computer and use it in GitHub Desktop.
Save hoanbka/e0a777b877cad07b61b7595811de2538 to your computer and use it in GitHub Desktop.
/**
* Created by Hoan Nguyen on 11/11/2017.
*/
//Note that: this solution is for array of Intergers ONLY
function diffArray(arr1, arr2) {
var output = [];
// Same, same; but different.
arr1.sort((a, b) => a - b);
arr2.sort((a, b) => a - b);
var i = 0, j = 0;
while (true) {
if (arr1[i] < arr2[j]) {
output.push(arr1[i]);
i++;
} else if (arr1[i] > arr2[j]) {
output.push(arr2[j]);
j++;
} else {
i++;
j++;
}
if (i == arr1.length && j == arr2.length) break;
if (i == arr1.length && j < arr2.length) {
for (var x = j; x < arr2.length; x++) {
output.push(arr2[x]);
}
break;
}
if (j == arr2.length && i < arr1.length) {
for (var y = i; y < arr1.length; y++) {
output.push(arr1[y]);
}
break;
}
}
return output;
}
function findDifference(arr1, arr2) {
var a = Array.from(new Set(arr1));
var b = Array.from(new Set(arr2));
var map = new Map();
var output = [];
for (var i = 0; i < a.length; i++) {
map.set(a[i], 1);
}
for (var i = 0; i < b.length; i++) {
if (map.has(b[i])) {
map.set(b[i], map.get(b[i]) + 1);
} else {
map.set(b[i], 1);
}
}
var keys = Array.from(map.keys());
for (var i = 0; i < keys.length; i++) {
if (map.get(keys[i]) === 1) output.push(keys[i]);
}
return output;
}
// diffArray([1, 4, 3, 5], [1, 2, 3, 4, 5, 8]);
console.log(diffArray([1, 4, 3, 5, 10], [1, 2, 3, 4, 5, 8]));
// console.log(diffArray([1, 4, 3, 10], [1, 2, 3, 4, 5]));
console.log(findDifference([1, 4, 3, 5, 10], [1, 2, 2, 3, 4, 5, 8]));
console.log(findDifference(["diorite", "andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite", "andesite", "grass", "dirt", "dead shrub"]));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment