I have two arrays of objects (Array1 and Array2) that I must combine in one array (result).
If an value is present in both arrays, it should be only once in the final array.
If a value is not present in any of the arrays, it needs to be added with the boolean set to true.
Here's the situation:
const Array1 = [
{value: "id1", name: "Element1", boolean: false},
{value: "id2", name: "Element2", boolean: false},
{value: "id3", name: "Element3", boolean: false}
]
const Array2 = [
{value: "id1", name: "Element1", boolean: false},
{value: "id2", name: "Element2", boolean: false},
{value: "id4", name: "Element4", boolean: false}
]
Expected output:
const result = [
{value: "id1", name: "Element1", boolean: false},
{value: "id2", name: "Element2", boolean: false},
{value: "id3", name: "Element3", boolean: true},
{value: "id4", name: "Element4", boolean: true}
]
You can easily achieve the result using Map
const Array1 = [
{ value: "id1", name: "Element1", boolean: false },
{ value: "id2", name: "Element2", boolean: false },
{ value: "id3", name: "Element3", boolean: false },
];
const Array2 = [
{ value: "id1", name: "Element1", boolean: false },
{ value: "id2", name: "Element2", boolean: false },
{ value: "id4", name: "Element4", boolean: false },
];
const map = new Map(Array1.map((o) => [o.value, [o]]));
Array2.forEach((o) =>
map.has(o.value) ? map.get(o.value).push(o) : map.set(o.value, [o])
);
const result = [...map.values()].map((arr) =>
arr.length > 1 ? arr[0] : { ...arr[0], boolean: true }
);
console.log(result);
/* This is not a part of answer. It is just to give the output full height. So IGNORE IT */
.as-console-wrapper { max-height: 100% !important; top: 0; }
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments