EN
JavaScript - group / grouping array items with reduce method
4 points
In this article, we're going to have a look at how to group array items with Array
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.
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.
xxxxxxxxxx
1
function groupItems(array, property) {
2
var reducer = function(groups, item) {
3
var name = item[property]
4
var group = groups[name] || (groups[name] = []);
5
group.push(item);
6
return groups;
7
};
8
return array.reduce(reducer, {});
9
}
10
11
12
// Usage example:
13
14
var array = [
15
{name: 'John', age: 25},
16
{name: 'Kate', age: 21},
17
{name: 'Pablo', age: 25},
18
{name: 'Denis', age: 25},
19
{name: 'Chris', age: 31}
20
];
21
22
var groups = groupItems(array, 'age'); // array will be grouped by 'age' property
23
24
25
console.log('[key]\t[group]');
26
27
for(var key in groups) {
28
var group = groups[key];
29
console.log('"' + key + '"\t' + JSON.stringify(group));
30
}
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.
xxxxxxxxxx
1
function getValue(object, path) {
2
var reducer = function(tmp, key) {
3
return tmp[key];
4
};
5
return path.reduce(reducer, object);
6
}
7
8
function groupItems(array, path) {
9
var reducer = function(groups, item) {
10
var name = getValue(item, path);
11
var group = groups[name] || (groups[name] = []);
12
group.push(item);
13
return groups;
14
};
15
return array.reduce(reducer, {});
16
}
17
18
19
// Usage example:
20
21
var path = ['details', 'age']; // array items will be grouped by `details.age`
22
23
var array = [
24
{name: 'John', details: {age: 25}},
25
{name: 'Kate', details: {age: 21}},
26
{name: 'Pablo', details: {age: 25}},
27
{name: 'Denis', details: {age: 25}},
28
{name: 'Chris', details: {age: 31}}
29
];
30
31
var groups = groupItems(array, path);
32
33
34
console.log('[key]\t[group]');
35
36
for(var key in groups) {
37
var group = groups[key];
38
console.log('"' + key + '"\t' + JSON.stringify(group));
39
}