Merge two n number of array of objects based on a key

I have two arrays:

Array 1:

[
    {old_clicks: 1, date: "2017-01-24" }, 
    { old_clicks: 4, date: "2017-01-22" },
    { old_clicks: 6, date: "2017-01-21" }
]

and array 2:

[
    { total_clicks:120, date: "2017-01-21" },
    { total_clicks: 100, date: "2017-01-19" }
]

I need to merge these two arrays based on date and get this:

[
    { old_clicks: 1,date: "2017-01-24", total_clicks: 0 },
    { old_clicks: 4, date: "2017-01-22", total_clicks: 0 },
    { old_clicks: 6, date: "2017-01-21", total_clicks: 120 },
    { old_clicks: 0, date: "2017-01-19", total_clicks: 100 },
]

I have tried this but this is not working as its not merging properly.

const arr1 = [
    { old_clicks: 1, date: "2017-01-24" }, 
    { old_clicks: 4, date: "2017-01-22" },
    { old_clicks: 6, date: "2017-01-21" }
];


const arr2 =  [
    { total_clicks:120, date: "2017-01-21" },
    { total_clicks: 100, date: "2017-01-19" }
];
        

const mergeById = (a1, a2) => a1.map(itm => ({
    ...a2.find((item) => (item.date=== itm.date)),
    ...itm
}));

console.log(mergeById(arr1,arr2))

55 thoughts on “Merge two n number of array of objects based on a key”

Leave a Comment