aweber-banner

Grouping Object Values by Key for JS Arrays

Grouping Object Values by Key for JS Arrays

So, this morning I needed to display a graph of values by month and the client’s API was returning something that looked like this:

[{
 “date”: “2022–05”,
 “employee”: 1000,
 “employer”: 500
}, {
 “date”: “2022–04”,
 “employee”: 1000,
 “employer”: 500
}, {
 “date”: “2022–04”,
 “employee”: 1000,
 “employer”: 500
}]


Having 2 objects with dates that fell in April, I needed to group my objects by month and sum their values before displaying them in my graph. Without wanting to use any packages, I set out to find some solutions.

SolutionL


Initialise an empty array and then use the forEach() method to loop over each object whilst using the includes() method to dictate whether the current iteration object should be added or appended.

const grouped = [];
res.forEach(it => {
  const existingDates = grouped.map(it => it.date);
  
  if (existingDates.includes(it.date)) {
    const existingMonth = grouped.find(ex => ex.date === it.date);
    existingMonth.employee += it.employee;
    existingMonth.employer += it.employer;
  } else {
    grouped.push({
      ...it,
      date: it.date,
    });
  }
});


Result

An array of objects grouped by date:


[{
 “date”: “2022–05”,
 “employee”: 1000,
 “employer”: 500
}, {
 “date”: “2022–04”,
 “employee”: 2000,
 “employer”: 100
}]