Skip to content

Instantly share code, notes, and snippets.

Created April 12, 2017 12:56
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 anonymous/8302f8ca7caef5b774dbe0bf49148075 to your computer and use it in GitHub Desktop.
Save anonymous/8302f8ca7caef5b774dbe0bf49148075 to your computer and use it in GitHub Desktop.
const mergeArrays = (a, b) => {
// Count occurrences of a value in an array
const countOccurrences = (array, value) => array.reduce((acc, current) => acc + (current === value));
// Whether there is the same number of occurrences of a value in two arrays
const isSameCount = (array1, array2, value) => countOccurrences(array1, value) === countOccurrences(array2, value);
const final = [];
for (let i = 0; i < b.length; i++) { // For each of b
if (!a.includes(b[i]) && !final.includes(b[i])) {
final[final.length] = b[i];
}
}
for (let i = 0; i < a.length; i++) { // For each of a
if (isSameCount(a, b, a[i]) && !final.includes(a[i])) {
final[final.length] = a[i];
}
else if (!final.includes(a[i]) && !b.includes(a[i])) {
final[final.length] = a[i];
}
}
return final.sort((a, b) => a - b);
};
var a = [1, 3, 40, 40, 50, 60, 60, 60];
var b = [2, 40, 40, 50, 50, 65];
var mergedArray = mergeArrays(a, b);
console.log(mergedArray);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment