Custom Interface -
interface Person {
name: string;
age: number;
city: string;
address?: string;
}
Data Arrays -
const people1: Person[] = [
{
name: "daniel",
age: 21,
city: 'NYC'
},
{
name: "kosta",
age: 28,
city: "NYC"
},
{
name: "yoav",
age: 28,
city: "NYC"
}
];
const people2: Person[] = [{
name: "daniel",
age: 21,
city: "NYC",
address: 'E. 43'
},
{
name: "simon",
age: 24,
city: "NYC",
address: 'E. 43'
},
{
name: "david",
age: 22,
city: "NYC",
address: 'E. 43'
},
{
name: "kosta",
age: 28,
city: "NYC",
address: 'E. 43'
}
];
Mapping keys for the data arrays -
const people1Map: ReadonlyMap<string, string | undefined> = new Map(
people1.map(
({
name, age, city, address
}) => [
`${name}|${age}|${city}`,
address
]
)
);
const people2Map: ReadonlyMap<string, string | undefined> = new Map(
people2.map(
({
name, age, city, address
}) => [
`${name}|${age}|${city}`,
address
]
)
);
Arrays for Matches and Unmatches -
let matchedPeople1: Person[] = []
let unmatchedPeople1: Person[] = []
let matchedPeople2: Person[] = []
let unmatchedPeople2: Person[] = []
Comparing data between arrays and storing matches or unmatches accordingly.
The desired output is as follows:
matchedPeople1:
[{ name: "daniel", age: 21, city: "NYC", address: 'E. 43' }, { name: "kosta", age: 28, city: "NYC", address: 'E. 43' } ]
matchedPeople2:
[{ name: "daniel", age: 21, city: "NYC", address: 'E. 43' }, { name: "kosta", age: 28, city: "NYC", address: 'E. 43' }]
unmatchedPeople1:
[{ name: "yoav", age: 28, city: "NYC" }]
unmatchedPeople2:
[{ name: "simon", age: 24, city: "NYC", address: 'E. 43' }, { name: "david", age: 22, city: "NYC", address: 'E. 43' }]