Languages
[Edit]
EN

JavaScript - group / grouping array items with reduce method

1 points
Created by:
Greg
5140

In this article, we're going to have a look at how to group array items with reduce method. This article shows two ways to use Array reduce method to group array by item property. Second one example shows how to group it with nested properties.

1. Group by object property example

This section contains simple grouping of the array by property. Array reduce method in below example takes two arguments:

  • function that converts array structure,
  • empty object that will be filled with groups.

To change group name it is necessary only to change property variable.

// ONLINE-RUNNER:browser;

var property = 'age'; // by this item property array will be grouped
var array = [
  { name: 'John',  age: 25 },
  { name: 'Kate',  age: 21 },
  { name: 'Pablo', age: 25 },
  { name: 'Denis', age: 25 },
  { name: 'Chris', age: 31 }
];

var groups = array.reduce(function(groups, item) {
  var name = item[property]
  var group = groups[name] || (groups[name] = [ ]);
  group.push(item);

  return groups;
}, { });

for(var key in groups) {
  var group = groups[key];
  console.log('"' + key + '" group contains ' + group.length + ' elements')
}

2. Group by nested object property example

In this section first example was modiffied to provide grouping by nested property.

To change group name it is necessary only to change path array to own one.

// ONLINE-RUNNER:browser;

var path = ['details', 'age']; // by this nested item property array will be grouped
var array = [
  { name: 'John',  details: { age: 25 } },
  { name: 'Kate',  details: { age: 21 } },
  { name: 'Pablo', details: { age: 25 } },
  { name: 'Denis', details: { age: 25 } },
  { name: 'Chris', details: { age: 31 } }
];

var groups = array.reduce(function(groups, item) {
  var name = path.reduce(function(data, key) {
    return data[key]
  }, item);

  var group = groups[name] || (groups[name] = [ ]);
  group.push(item);

  return groups;
}, { });

for(var key in groups) {
  var group = groups[key];
  console.log('"' + key + '" group contains ' + group.length + ' elements')
}

 

Native Advertising
50 000 ad impressions - 449$
🚀
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

❤️💻 🙂

Join