Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.