Calling reduce to sum array of objects returns NaN

You could use a start value and the add only one value from the array. var temp=[{“name”:”Agency”,”y”:32,”drilldown”:{“name”:”Agency”,”categories”:[“APPS & SI”,”ERS”],”data”:[24,8]}},{“name”:”ER”,”y”:60,”drilldown”:{“name”:”ER”,”categories”:[“APPS & SI”,”ERS”],”data”:[7,53]}},{“name”:”Direct”,”y”:60,”drilldown”:{“name”:”Direct”,”categories”:[“APPS & SI”,”ERS”],”data”:[31,29]}}]; var reduced = temp.reduce(function (r, a) { return r + a.y; // ^^^ use the last result without property }, 0); // ^^^ add a start value console.log(reduced) // r

Scala : fold vs foldLeft

The method fold (originally added for parallel computation) is less powerful than foldLeft in terms of types it can be applied to. Its signature is: def fold[A1 >: A](z: A1)(op: (A1, A1) => A1): A1 This means that the type over which the folding is done has to be a supertype of the collection element … Read more

Spark groupByKey alternative

groupByKey is fine for the case when we want a “smallish” collection of values per key, as in the question. TL;DR The “do not use” warning on groupByKey applies for two general cases: 1) You want to aggregate over the values: DON’T: rdd.groupByKey().mapValues(_.sum) DO: rdd.reduceByKey(_ + _) In this case, groupByKey will waste resouces materializing … Read more

In Stream reduce method, must the identity always be 0 for sum and 1 for multiplication?

The identity value is a value, such that x op identity = x. This is a concept which is not unique to Java Streams, see for example on Wikipedia. It lists some examples of identity elements, some of them can be directly expressed in Java code, e.g. reduce(“”, String::concat) reduce(true, (a,b) -> a&&b) reduce(false, (a,b) … Read more

What is the ‘pythonic’ equivalent to the ‘fold’ function from functional programming?

The Pythonic way of summing an array is using sum. For other purposes, you can sometimes use some combination of reduce (from the functools module) and the operator module, e.g.: def product(xs): return reduce(operator.mul, xs, 1) Be aware that reduce is actually a foldl, in Haskell terms. There is no special syntax to perform folds, … Read more