Given the following ArrayList containing a couple of items having a name and a value:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
List<Item> items = Arrays.asList( | |
new Item("A", 10), | |
new Item("B", 20), | |
new Item("C", 30), | |
new Item("A", 40), | |
new Item("B", 50), | |
new Item("C", 60)); |
Let’s assume we want to group the items by name and sum up all values. With the aid of Java 8, we can do it as follows:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Map<String, Integer> accumulator = items.stream().collect(Collectors.groupingBy(Item::getName, Collectors.summingInt(Item::getValue))); |
In order to get an ArrayList again, we can iterate over the map, create new items from each entry and add this to a list:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
List<Item> result = new ArrayList<>(); | |
for (Map.Entry<String,Integer> entry : accumulator.entrySet()){ | |
result.add(new Item(entry.getKey(), entry.getValue())); | |
} |
I was wondering how to do the same calculation using JavaScript as there is no similar goupingBy function. And here it is… We need to implement the groupingBy functionality by using the reduce function.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var arr = [ | |
{ name: "A", value: 10 }, | |
{ name: "B", value: 20 }, | |
{ name: "C", value: 30 }, | |
{ name: "A", value: 40 }, | |
{ name: "B", value: 50 }, | |
{ name: "C", value: 60 }]; | |
var accumulated = arr.reduce(function(accumulator, element) { | |
var currentValue = accumulator[element.name]; | |
if(currentValue !== undefined) { | |
accumulator[element.name] = currentValue + element.value; | |
} | |
else { | |
accumulator[element.name] = element.value; | |
} | |
return accumulator; | |
}, {}); | |
var result = Object.keys(accumulated).map(function(k) {return {name: k, value: accumulated[k]}}) |