Skip to content
Advertisement

Combine two array into one while getting the sum of instances in second array

I have two arrays. The first array is this:

arrayOne = [
{id: 1, type: 'Animal', legs: 4},
{id: 2, type: 'Animal', legs: 2},
{id: 3, type: 'Animal', legs: 8},
{id: 4, type: 'Plant', legs: 0},
]

This is the second array:

arrayTwo = [
{typeId: 1, processing: 2},
{typeId: 1, processing: 3},
{typeId: 1, approved: 3},
{typeId: 1, approved: 2},
{typeId: 1, disapproved: 3},
{typeId: 1, disapproved: 2},
{typeId: 2, approved: 2},
{typeId: 2, disapproved: 1},
{typeId: 2, disapproved: 1},
{typeId: 3, approved: 2},
{typeId: 4, disapproved: 3},
]

If id of arrayOne is equal to typeId of arrayTwo, then append arrayTwo into arrayOne and sum up the number of processing, approved and disapproved. This is my desiredArray:

desiredArray = [
{id: 1, type: 'Animal', legs: 4, processing: 5, approved: 5, disapproved: 5},
{id: 2, type: 'Animal', legs: 2, approved: 2, disapproved: 2},
{id: 3, type: 'Animal', legs: 8, approved: 2},
{id: 4, type: 'Plant', legs: 0, disapproved: 3},
]

Advertisement

Answer

You can first reduce the second array and then map it to the first one:

const arrayOne = [{id: 1, type: 'Animal', legs: 4},{id: 2, type: 'Animal', legs: 2},{id: 3, type: 'Animal', legs: 8},{id: 4, type: 'Plant', legs: 0},];
const arrayTwo = [{typeId: 1, processing: 2},{typeId: 1, processing: 3},{typeId: 1, approved: 3},{typeId: 1, approved: 2},{typeId: 1, disapproved: 3},{typeId: 1, disapproved: 2},{typeId: 2, approved: 2},{typeId: 2, disapproved: 1},{typeId: 2, disapproved: 1},{typeId: 3, approved: 2},{typeId: 4, disapproved: 3},];

const reduced = arrayTwo.reduce((a,{typeId, ...rest})=>{
    a[typeId] ??= {};
    Object.entries(rest).forEach(([k,v])=>{
        a[typeId][k] ??= 0;
        a[typeId][k]+=v;
    });
    return a;
},{});

const result = arrayOne.map(o=>({...o, ...reduced[o.id]}));

console.log(result);
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement