1

I am trying to sum up the numbers inside an array e.g. from here: https://jsfiddle.net/4r8dtxhz/12/

here is the Code:

var someObj = [{name:"hi", series: [1,2,10,4,5,6]},{name:"ho",series:[3,7,6,9,12,1,3,20,3,1]}]
    
for (var doc of someObj) {
           
      this.min = doc.series.reduce((agg,val) => val < agg? val:agg, doc.series[0]);
      this.max = doc.series.reduce((agg,val) => val > agg? val:agg, doc.series[0]);
            
}
console.log(max)
    
var test = Array.from(someObj.map((doc)=>doc.series)).reduce((accumulator, currentValue) => accumulator + currentValue);
console.log(typeof test)
console.log(test)

I was expecting the reduce function to sum up the numbers in the object series array... so I am wondering what goes wrong here?

dwjohnston
  • 11,163
  • 32
  • 99
  • 194
MMM
  • 287
  • 1
  • 5
  • 17

2 Answers2

3

Your map function is producing an two dimensional array of [someObj[0].series, someObj[1].series].

When you add two arrays together using the + operator in your reducer, it converts them to a string and concatenates the string.

If you want to create an array of the sum of each series, introduce another map function which has a reduce inside it.

jordrake
  • 500
  • 3
  • 9
2

You are missing a step to flatten the result of your map step. Your code

someObj.map((doc) => doc.series)

will return an array of arrays (or 2D array) rather than a flat array.

If you add a step to flatten the 2D array after your map step—for example by

.reduce((flattened, series) => flattened.concat(series))

using Array.reduce again—you will get the expected result.

Note that you should always provide an initial value for the accumulator of reduce (in your case 0 was missing for the summation) to assure that + is getting resolved correctly to number addition (otherwise it will be string concatenation, e.g. [1]+[2] === '12'). Also, Array.from wasn't necessary since someObj already is an array (Array.from converts from an Iterable object to Array).

var someObj = [{name:"hi", series: [1,2,10,4,5,6]},{name:"ho",series:[3,7,6,9,12,1,3,20,3,1]}]

for (var doc of someObj) {

        this.min = doc.series.reduce((agg,val) => val < agg? val:agg, doc.series[0]);

        this.max = doc.series.reduce((agg,val) => val > agg? val:agg, doc.series[0]);

      }
console.log(max)

var test = someObj.map((doc)=>doc.series)
  .reduce((flattened, series) => flattened.concat(series))
  .reduce((accumulator, currentValue) => accumulator + currentValue, 0);

console.log(typeof test)
console.log(test)
FK82
  • 4,907
  • 4
  • 29
  • 42