Created
October 5, 2022 00:04
-
-
Save sagnol/cdf2fb915155d5b612c4cd6422c0f232 to your computer and use it in GitHub Desktop.
Nodejs innerjoin
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
// See | |
// https://stackoverflow.com/questions/42429023/how-can-i-perform-an-inner-join-with-two-object-arrays-in-javascript#answer-42429128 | |
const a = [ | |
{id: 4, name: 'Greg'}, | |
{id: 1, name: 'David'}, | |
{id: 2, name: 'John'}, | |
{id: 3, name: 'Matt'}, | |
]; | |
const b = [ | |
{id: 5, name: 'Mathew', position: '1'}, | |
{id: 6, name: 'Gracia', position: '2'}, | |
{id: 2, name: 'John', position: '2'}, | |
{id: 3, name: 'Matt', position: '2'}, | |
]; | |
const r = a.filter(({ id: idv }) => b.every(({ id: idc }) => idv !== idc)); | |
const newArr = b.concat(r).map((v) => v.position ? v : { ...v, position: null }); | |
console.log(JSON.stringify(newArr)); | |
// Result | |
//[{"id":5,"name":"Mathew","position":"1"},{"id":6,"name":"Gracia","position":"2"},{"id":2,"name":"John","position":"2"},{"id":3,"name":"Matt","position":"2"},{"id":4,"name":"Greg","position":null},{"id":1,"name":"David","position":null}] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment