Skip to content

Instantly share code, notes, and snippets.

@C5H8NNaO4
Last active July 15, 2020 21:07
Show Gist options
  • Save C5H8NNaO4/67c05bbf716b3f4f24494c3419ec6757 to your computer and use it in GitHub Desktop.
Save C5H8NNaO4/67c05bbf716b3f4f24494c3419ec6757 to your computer and use it in GitHub Desktop.
Left join
//Closed question on Stackoverflow
//https://stackoverflow.com/questions/62923537/create-new-object-using-two-objects-that-share-a-prop#
users = [
{userId: 1, name: "John", favoriteFruit: "Apple"},
{userId: 2, name: "Jerry", favoriteFruit: "Pear"},
{userId: 3, name: "Linda", favoriteFruit: "Peach"},
{userId: 4, name: "Cruz", favoriteFruit: "Banana"},
];
cars = [
{userId: 1, carModel: "GT200", color: "Blue"},
{userId: 1, carModel: "GT300", color: "Green"},
{userId: 2, carModel: "F200", color: "Black"},
{userId: 4, carModel: "F1200", color: "White"},
{userId: 4, carModel: "RT600", color: "Pink"},
{userId: 3, carModel: "GT200", color: "Yellow"},
];
function leftJoin(l, r, on) {
const lkp = r.reduce((acc, cur) => {
acc[cur[on]] = cur;
return acc;
}, {})
return l.map((e) => {
const from = lkp[e[on]];
return {...e, ...from}
})
}
const joined = leftJoin(cars, users, 'userId');
console.log (joined)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment