Created
August 16, 2018 07:07
-
-
Save samundrak/6302380c3caa59cfb2d5504ebe0a0915 to your computer and use it in GitHub Desktop.
Outer Join of array in js using Map, Set, Array
This file contains hidden or 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 a = [ | |
{ id: 3, name: 'Matt' }, | |
{ id: 4, name: 'Greg' }, | |
{ id: 1, name: 'David' }, | |
{ id: 2, name: 'John' }, | |
]; | |
const b = [ | |
{ id: 7, position: 'Outlier' }, | |
{ id: 2, position: 'Leader' }, | |
{ id: 3, position: 'Captain' }, | |
{ id: 6, position: 'Rogue' }, | |
{ id: 4, position: 'VP' }, | |
{ id: 5, position: 'Pawn' }, | |
]; | |
function comparer(a, b) { | |
if (a < b) { | |
return -1; | |
} | |
if (a > b) { | |
return 1; | |
} | |
return 0; | |
} | |
const tableA = new Map(a.map(item => [item.id, item])); | |
const tableB = new Map(b.map(item => [item.id, item])); | |
const ids = new Set( | |
a | |
.concat(b) | |
.map(item => item.id) | |
.sort(comparer), | |
); | |
const outerJoin = Array.from(ids.values()).map(item => { | |
return { | |
...tableA.get(item), | |
...tableB.get(item), | |
}; | |
}); | |
console.log(outerJoin); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment