Combine two different arrays in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Suppose we have two arrays, the first array contains the scheduled date for some events and the second array contains the names of those events, like this −

const dates = [
   {
      id:"1",
      date:"2017-11-07"
   },
   {
      id:"1",
      date:"2017-11-08"
   },
   {
      id:"2",
      date:"2017-11-07"
   },
   {
      id:"2",
      date:"2017-11-08"
   }
];
const names = [
   {
      id:"1",
      name:"Pervies, Peter"
   },
   {
      id:"2",
      name:"Ming, Edmund"
   }
];

We are required to write a JavaScript function that takes in two such array and combines the event names with their corresponding dates based on the id property.

Therefore, for these arrays, the output should look like −

const output = [
   {
      id:"1",
      name:"Pervies, Peter",
      details:[
         {date:"2017-11-07"},
         {date:"2017-11-08"}
      ]
   },
   {
      id:"2",
      name:"Ming, Edmund",
      details:[
         {date:"2017-11-07"},
         {date:"2017-11-08"}
      ]
   }
]

Example

The code for this will be −

const dates = [
   {
      id:"1",
      date:"2017-11-07"
   },
   {
      id:"1",
      date:"2017-11-08"
   },
   {
      id:"2",
      date:"2017-11-07"
   },
   {
      id:"2",
      date:"2017-11-08"
   }
];
const names = [
   {
      id:"1",
      name:"Pervies, Peter"
   },
   {
      id:"2",
      name:"Ming, Edmund"
   }
];
const combineArrays = (dates, names) => {
   const res = [];
   dates.forEach(el => {
      const bool = !res.some(item => {
         return item.id == el.id;
      });
      if(bool){
         let combined = {};
         combined.id = el.id;
         combined.details = combined.details || [];
         combined.details.push({
            "date": el.date
         });
         res.push(combined);
      }else{
         res.find(item => {
            return item.id === el.id;
         })
         .details.push({
            "date": el.date
         });
      };
   });
   res.forEach(el => {
      const bool = names.some(item => {
         return item.id === el.id;
      });
      if(bool){
         el.name = names.find(name => {
            return name.id === el.id;
         }).name;
      };
   });
   return res;
};
console.log(JSON.stringify(combineArrays(dates, names), undefined, 4));

Output

The output in the console −

[
   {
      "id": "1",
      "details": [
         {
            "date": "2017-11-07"
         },
         {
            "date": "2017-11-08"
         }
      ],
      "name": "Pervies, Peter"
   },
   {
      "id": "2",
      "details": [
         {
            "date": "2017-11-07"
         },
         {
            "date": "2017-11-08"
         }
      ],
      "name": "Ming, Edmund"
   }
]
raja
Published on 12-Oct-2020 11:28:21
Advertisements