• Andre DiCioccio

Array Grouping in Javascript


In Javascript, it is common to have an array of objects which might have multiple properties.


Sometimes you need to sort through though and categorise or group those items based upon properties.


So what if you need to go through a JavaScript array of items and group those items based upon one of the properties?


For example, let's say that you have an array of items such as:


const items = [
  { name: 'red', category: 'colors' },
  { name: 'green', category: 'colors' },
  { name: 'one', category: 'numbers' }
];

It is clear to us reading it that there are two "colors" items and a single "numbers" item, but we need a way for JavaScript to sort out and group those.


Here is where the array.reduce() method comes in.



Using the array.reduce() method to group objects from an array.


const groupByProperty = items.reduce((group, item) => {
  const { category } = product;
  group[category] = group[category] ?? [];
  group[category].push(item);
  return group;
}, {});



This will clearly separate the items in the array and also put them into an itemised object so that they can be easily accessed and manipulated as required.


console.log(groupByProperty);
// {
//   'colors': [
//     { name: 'red', category: 'colors' }, 
//     { name: 'green', category: 'colors' },
//   ],
//   'numbers': [
//     { name: 'one', category: 'numbers' }
//   ]
// }


The array.groupBy() method


Note that there is a new method, currently at stage 3 proposal, which will make this more succinct:


const groupByProperty = items.groupBy(item => {
  return item.category;
});


This method can also be used today through polyfils such as: https://github.com/zloirock/core-js#array-grouping







7 views

Recent Posts

See All