Created
April 12, 2017 12:56
-
-
Save anonymous/8302f8ca7caef5b774dbe0bf49148075 to your computer and use it in GitHub Desktop.
This file contains 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
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