Example data -
const arr = [{name: "q",age: 10,size: "M",},{name: "w",age: 10,size: "S",},{name: "e",age: 10,size: "M",},];
const arr2 = [{name: "q",age: 10,size: "M",location: "NYC"},{name: "w",age: 10,size: "S",location: "DC"},{name: "i",age: 10,size: "S",location: "NYC"},{name: "x",age: 10,size: "S",location: "NYC"},];
The logic -
const set = new Set(arr2.map(({name, size}) => size + "/" + name));
const x = [], y = [];
for (let obj of arr) {
(set.has(obj.size + "/" + obj.name) ? x : y).push(obj);
}
Result -
x:
[
{
"name": "q",
"age": 10,
"size": "M"
},
{
"name": "w",
"age": 10,
"size": "S"
}
]
y:
[
{
"name": "e",
"age": 10,
"size": "M"
}
]
How can I assign the location to arr. wanted result -
x:
[
{
"name": "q",
"age": 10,
"size": "M",
"location": "NYC"
},
{
"name": "w",
"age": 10,
"size": "S",
"location": "DC"
}
]
y:
[
{
"name": "e",
"age": 10,
"size": "M",
}
]
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Use an object or Map instead of Set. Then you can save the location along with the name and size.
const arr = [{name: "q",age: 10,size: "M",},{name: "w",age: 10,size: "S",},{name: "e",age: 10,size: "M",},];
const arr2 = [{name: "q",age: 10,size: "M",location: "NYC"},{name: "w",age: 10,size: "S",location: "DC"},{name: "i",age: 10,size: "S",location: "NYC"},{name: "x",age: 10,size: "S",location: "NYC"},];
const map = new Map(arr2.map(({name, size, location}) => [size + "/" + name, location]));
const x = [], y = [];
for (let obj of arr) {
let location = map.get(obj.size + "/" + obj.name);
if (location) {
obj.location = location;
x.push(obj);
} else {
y.push(obj);
}
}
console.log(x);
console.log(y);