Definition of Interface -
interface I {
name: string;
age: number;
size?: string;
}
Arrays Initialization -
let firstArrayMatches: I[] = [];
let firstArrayUnmatches: I[] = [];
let secondArrayMatches: I[] = [];
let secondArrayUnmatches: I[] = [];
Initial Values for First Array -
const firstArray: I[] = [
{
name: 'daniel',
age: 30
},
{
name: 'tamir',
age: 30
}
]
Initial Values for Second Array -
const secondArray: I[] = [
{
name: 'daniel',
age: 30,
size: 'm'
},
{
name: 'ariel',
age: 28,
size: 'm'
}
]
Mapping the Elements in secondArray
to return a string[]
-
const secondArrayIndexes = secondArray.map(({ name, age }) => name + '/' + age);
Iterate through the firstArray
, if there is a match push the object into firstArrayMatches
and push ...secondArray.splice(match, 1)
into secondArrayMatches
. If no match, push the object into firstArrayUnmatches
and assign the remaining elements in the second array to secondArrayUnmatches
.
for (const o of firstArray) {
const match = secondArrayIndexes.indexOf(o.name + '/' + o.age);
if (match >= 0) {
firstArrayMatches.push(o);
secondArrayMatches.push(...secondArray.splice(match, 1));
} else {
firstArrayUnmatches.push(o);
}
}
secondArrayUnmatches = secondArray;
Output Results -
console.log('First Matching Objects: '+ JSON.stringify(firstArrayMatches))
console.log('First Unmatched Objects: '+ JSON.stringify(firstArrayUnmatches))
console.log('Second Matching Objects: '+ JSON.stringify(secondArrayMatches))
console.log('Second Unmatched Objects: '+ JSON.stringify(secondArrayUnmatches))
Expected Output -
First Matching Objects:
[{"name":"daniel","age":30,"size":"m"}]
First Unmatched Objects:
[{"name":"tamir","age":30}]
Second Matching Objects:
[{"name":"daniel","age":30,"size":"m"}]
Second Unmatched Objects:
[{"name":"ariel","age":28,"size":"m"}]
The function should transfer properties from the second array to the first array if there is a match.