Search code examples
javascriptalgorithmfilterarray-mergearrayobject

Merge array of object dynamically with same key and create it as new data (array of object)


Ive got some array of object I want to merge array of object with the same key and create it as new object based on the key and value

const data =[{
  date:"19",
  status:"in",
hour:”12:00”

},{

  date:"19",
  status:"in",
hour:”12:20”
},{
  date:"19",
  status:"in",
hour:”12:43”
},{
  date:"19",
  status:"out",
hour:”16:16”

},{
  date:"20",
  status:"in",
hour:07:30”
},{
  date:"20",
  status:"out",
hour:”14:40”
},{
  date:"21",
  status:"in",
hour:”08:12”
}
]

Here is the result that i want


result =[{
date:”19”,
hourIn= “12:00”,
hourOut= “16:16”,      
}, {
  date:"20",
  hourIn:"07:30",
hourOut:14:40”
},{
  date:"21",
hourIn:”08:12”,
hourOut:”-“}]

How i suppose to solve this problem ?


Solution

  • Here's how I did it, I iterated through the data, checking if that date had already been passed.

    If not, I checked if the status was in or out, then set the hour and the date.

    If it had been passed, I checked the status, then checked if the hour was earlier than the hourIn or later than the hourOut already set.

    let result={};
    const data=[{date:"19",status:"in",hour:"12: 00"},{date:"19",status:"in",hour:"12:20"},{date:"19",status:"in",hour:"12:43"},{date:"19",status:"out",hour:"16:16"},{date:"20",status:"in",hour:"07:30"},{date:"20",status:"out",hour:"14:40"},{date:"21",status:"in",hour:"08:12"}];
    
    data.forEach(({ date, status, hour }) => {
      if (date in result) {
        if (status == 'in' && hour < result[date].hourIn) result[date].hourIn = hour;
        else if (status == 'out' && hour > result[date].hourOut) result[date].hourOut = hour;
      } else result[date] = {
        date,
        hourIn: status == 'in' ? hour : '-',
        hourOut: status == 'out' ? hour : '-'
      };
    });
    
    result = Object.values(result);
    console.log(result);