Stackoverflow 45746989

https://stackoverflow.com/a/45746989/4763083

by Korah Babu Varghese

JavaScript

const arr =  [
	{ id: '8',
   name: 'hfh',
   date: '2017-03-14',
   perDayIncident: [{g:5,l:6},{g:5,l:6},{g:5,l:6}] },
 { id: '7',
   name: 'onion',
   date: '2017-03-14',
   perDayIncident: []},
 { id: '6',
   name: 'onion',
   date: '2017-03-14',
   perDayIncident: [{g:5,l:6},{g:5,l:6}]},
 { id: '2',
   name: 'Ready-to-Serve Chocolate Drink',
   date: '2017-01-01',
   perDayIncident: [{g:5,l:6},{g:5,l:6}]} 
];

const reducedArray = arr.reduce((acc, next) => { // acc stands for accumulator
  const lastItemIndex = acc.length -1;
  const accHasContent = acc.length >= 1;

  if(accHasContent && acc[lastItemIndex].date == next.date) {
    acc[lastItemIndex].perDayIncident.push(next.perDayIncident);
  } else {
    // first time seeing this entry. add it!
    // acc[lastItemIndex +1] = next;
    acc[lastItemIndex +1] = { date: next.date, perDayIncident: next.perDayIncident };
  }
  return acc;
}, []);

console.log(reducedArray)