groupingBy in JavaScript

Given the following ArrayList containing a couple of items having a name and a value:


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:


Map<String, Integer> accumulator = items.stream().collect(Collectors.groupingBy(Item::getName, Collectors.summingInt(Item::getValue)));

view raw

groupingBy.java

hosted with ❤ by GitHub

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:


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.


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

 

Kommentar verfassen

Trage deine Daten unten ein oder klicke ein Icon um dich einzuloggen:

WordPress.com-Logo

Du kommentierst mit Deinem WordPress.com-Konto. Abmelden /  Ändern )

Twitter-Bild

Du kommentierst mit Deinem Twitter-Konto. Abmelden /  Ändern )

Facebook-Foto

Du kommentierst mit Deinem Facebook-Konto. Abmelden /  Ändern )

Verbinde mit %s