Top community members
All Wiki Articles Create Wiki Article

In the past we had a dream,
to have place where we could share IT knowledge,
to ask questions without fear that someone will judge us.

Now we are a group of people who make this dream come true. ❤ 💻

If you think sharing knowledge and helping other is valuable.

join our community - Click here

JavaScript - group / grouping array items with reduce method

0 contributions
1 points

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')
}

 

0 contributions

Suggested wiki articles:

Suggested findings

Let's do the work and have some fun
  • Dirask is online IT community for professionals and hobbyist to share their knowledge and help each other in extraordinary easy way. ❤ 💻 🙂
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    we will help you. 👍 ✔ 🦄
Read more