JavaScript: compare array element properties, and if identical, combine


Suppose, we have an array of objects that contains information about some data storage devices like this −

const drives = [
   {size:"900GB", count:3},
   {size:"900GB", count:100},
   {size:"1200GB", count:5},
   {size:"900GB", count:1}
];

Notice like how the same size comes multiple times.

We are required to write a function that takes in one such array and consolidate all repeated sizes into just one single array index and obviously adding up their counts.

Example

const drives = [
   {size:"900GB", count:3},
   {size:"900GB", count:100},
    {size:"1200GB", count:5},
   {size:"900GB", count:1}
];
const groupDrives = (arr = []) => {
   const map = drives.reduce((map, e) => {
      if (e.size in map) map[e.size].count += e.count
      else map[e.size] = e
         return map;
   }, {})
   const result = Object.keys(map).map(function (k) {
      return this[k]
   }, map);
   return result;
}
console.log(groupDrives(drives));

Output

And the output in the console will be −

[ { size: '900GB', count: 104 }, { size: '1200GB', count: 5 } ]

Updated on: 23-Nov-2020

49 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements