'JS - function that gets 2 arrays and return 4 - matches & unmatches from each & and assign property when there is a match
I made a demo for explaning the question -
Empty arrays -
let firstArrayMatches = [];
let firstArrayUnmatches = [];
let secondArrayMatches = [];
let secondArrayUnmatches = [];
The first array -
const firstArray = [
{
name: 'daniel',
age: 30
},
{
name: 'tamir',
age: 30
}
]
The second array -
const secondArray = [
{
name: 'daniel',
age: 30,
size: 'm'
},
{
name: 'ariel',
age: 28,
size: 'm'
}
]
Mapping the secondArray return key -
const secondArrayIndexes = secondArray.map(({ name, age }) => name + '/' + age);
loop through the firstArray, If match push the object into firstArrayMatches & push ...secondArray.splice(match, 1) into secondArrayMatches, else push object into firstArrayUnmatches, And assing the second array into 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;
This is what I'm getting right now on log -
first match: [{"name":"daniel","age":30}]
first unmatch: [{"name":"tamir","age":30}]
second match: [{"name":"daniel","age":30,"size":"m"}]
second unmatch: [{"name":"ariel","age":28,"size":"m"}]
Wanted output -
first match: [{"name":"daniel","age":30,"size":"m"}]
first unmatch: [{"name":"tamir","age":30}]
second match: [{"name":"daniel","age":30,"size":"m"}]
second unmatch: [{"name":"ariel","age":28,"size":"m"}]
I got another question - I'm not sure right now if when there is a match the secondArrayMatches will get the match if his place on the array isn't the same as the match
And I can't figure out how to assing a property when there is a match.
Would love to hear about another method to do what I want to. Thanks in advance for any help
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
