0

dailyTask=[ { subject: 'Documentation', owner_id: 1 }, { subject: 'SERVICES', owner_id: 2 } ]; emails=[ { employee_id: 1, email_id: 'abcd@gmail.com' }, { employee_id: 2, email_id: 'abcdef@gmail.com' } ];

merge two arrays on keys owner_id and employee_id and the required result is shown below

output=[ {employee_id:1,owner_id:1,email_id:'abcd@gmail.com',subject:'Documentation'}, {employee_id:2,owner_id:2,email_id:'abcdef@gmail.com',subject:'SERVICES'} ];

  • I'm not sure of what you're asking, but it has to merge when both id et owner are the same ? It could be quite long on long arrays. – Vollfeiw Apr 09 '21 at 11:11
  • 1
    https://stackoverflow.com/questions/19480008/javascript-merging-objects-by-id This post should be helpful – David Apr 09 '21 at 11:11
  • owner_id and employee_id should be matched –  Apr 09 '21 at 11:13
  • @David 's linked answer will help, just change the `id:item.id` by `employee_id: item.owner_id`. Keep in mind that this will be slow on big arrays. – Vollfeiw Apr 09 '21 at 11:16

1 Answers1

0

You can achieve this using Array.reduce & Object.values

const dailyTasks = [{subject:'Documentation',owner_id:1},{subject:'SERVICES',owner_id:2}];

const emails = [{employee_id:1,email_id:'abcd@gmail.com'},{employee_id:2,email_id:'abcdef@gmail.com'}];

const mergeArrays = (tasks, emails) => {
    return Object.values(tasks.reduce((acc,task) => {
    //fetch the matching email from the list of emails based on employee_id and owner_id
        const matchingEmail = emails.find(({employee_id}) => employee_id === task.owner_id);
        //add/update the object with the task & matching email
        acc[task.owner_id] = {
            ...(acc[task.owner_id] || {}),
            ...task,
            ...matchingEmail
        }
        return acc;
    }, {}));
}

console.log(mergeArrays(dailyTasks, emails));
.as-console-wrapper {
  max-height: 100% !important;
}
Nithish
  • 5,393
  • 2
  • 9
  • 24