Interface -
interface I {
name: string;
age: number;
size: string;
location?: string;
}
Empty arrays -
let firstArrayMatches: I[] = [];
let firstArrayUnmatches: I[] = [];
let secondArrayMatches: I[] = [];
let secondArrayUnmatches: I[] = [];
Arrays -
const firstArray: I[] = [
{
name: 'daniel',
age: 30,
size: 'm'
},
{
name: 'tamir',
age: 30,
size: 'm'
},
]
const secondArray: I[] = [
{
name: 'daniel',
age: 30,
size: 's'
},
{
name: 'ariel',
age: 28,
size: 'm'
},
]
Create new map from second array (Ignore second string it's for something else in mt real code) -
const map = new Map<string, string>(
secondArray.map(
({
name
}) => [
name,
'firstArray'
])
)
Run on first array -
for (const o of firstArray) {
const match = map.get(
o.name
)
if(match) {
firstArrayMatches.push(o);
} else {
firstArrayUnmatches.push(o);
}
}
Log -
First array -
console.log(JSON.stringify(firstArrayMatches))
"match: [{"name":"daniel","age":30,"size":"m"}]"
Second array -
console.log(firstArrayUnmatches)
[{
"name": "tamir",
"age": 30,
"size": "m"
}]
Right now my function is able to return only matches and unmatches from the first array, how can I get the second array matches and unmatches?
The following solution will work only if there are no duplicates on the name of secondArray. (I hope it because you create a Map from it)
// create index of second array
const secondArrayIndexes = Array.from(map.keys());
// OR const secondArrayIndexes = secondArray.map(({ name }) => name);
for (const o of firstArray) {
// get index of o.name
const match = secondArrayIndexes.indexOf(o.name);
if (match >= 0) {
firstArrayMatches.push(o);
secondArrayMatches.push(...secondArray.splice(match, 1));
} else {
firstArrayUnmatches.push(o);
}
}
// finally secondArray become secondArrayUnmatches
// you should create copy first if you use secondArray after this
secondArrayUnmatches = secondArray;