Group by, and sum, and generate an object for each array in JavaScript

let data =[ {“id”:”2018″, “name”:”test”, “total”:1200}, {“id”:”2019″, “name”:”wath”, “total”:1500}, {“id”:”2019″, “name”:”wath”, “total”:1800}, {“id”:”2020″, “name”:”zooi”, “total”:1000}, ]; let map = data.reduce((prev, next) =>{ if (next.id in prev) { prev[next.id].total += next.total; } else { prev[next.id] = next; } return prev; }, {}); let result = Object.keys(map).map(id => map[id]); console.log(result);

Java Stream: divide into two lists by boolean predicate

Collectors.partitioningBy: Map<Boolean, List<Employee>> partitioned = listOfEmployees.stream().collect( Collectors.partitioningBy(Employee::isActive)); The resulting map contains two lists, corresponding to whether or not the predicate was matched: List<Employee> activeEmployees = partitioned.get(true); List<Employee> formerEmployees = partitioned.get(false); There are a couple of reasons to use partitioningBy over groupingBy (as suggested by Juan Carlos Mendoza): Firstly, the parameter of groupingBy is a Function<Employee, … Read more

How to early break reduce() method?

UPDATE Some of the commentators make a good point that the original array is being mutated in order to break early inside the .reduce() logic. Therefore, I’ve modified the answer slightly by adding a .slice(0) before calling a follow-on .reduce() step, yielding a copy of the original array. NOTE: Similar ops that accomplish the same … Read more

Difference between reduce and foldLeft/fold in functional programming (particularly Scala and Scala APIs)?

reduce vs foldLeft A big big difference, not mentioned in any other stackoverflow answer relating to this topic clearly, is that reduce should be given a commutative monoid, i.e. an operation that is both commutative and associative. This means the operation can be parallelized. This distinction is very important for Big Data / MPP / … Read more

Sum JavaScript object propertyA values with the same object propertyB in an array of objects

Rather than using a for loop and pushing values, you can directly use map and reduce: let objArr = [ {key: ‘Mon Sep 23 2013 00:00:00 GMT-0400’, val: 42}, {key: ‘Mon Sep 24 2013 00:00:00 GMT-0400’, val: 78}, {key: ‘Mon Sep 25 2013 00:00:00 GMT-0400’, val: 23}, {key: ‘Mon Sep 23 2013 00:00:00 GMT-0400’, val: … Read more