Skip to content

Instantly share code, notes, and snippets.

@samundrak
Created August 16, 2018 07:07
Show Gist options
  • Save samundrak/6302380c3caa59cfb2d5504ebe0a0915 to your computer and use it in GitHub Desktop.
Save samundrak/6302380c3caa59cfb2d5504ebe0a0915 to your computer and use it in GitHub Desktop.
Outer Join of array in js using Map, Set, Array
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