0

I have a function that needs to take an array from each in a group of documents, and sum each position in each array with it's index 'partner' at the [n]th position.

The arrays look something like this......

[300, 230, 45, 0, 0, 0]
[200, 100, 0, 0, 0, 0]
[2, 1, 0, 0, 0, 0]
...

From which I would want to return [502, 331, 45, 0, 0, 0]. Using this question which is asking almost the same thing, I copied a reduce function, so my function now looks like this...

this.projects.forEach(function (project) {
    let arrays = project.yearsTotal
    result = arrays.reduce(function (r, a) {
        a.forEach(function (b, i) {
            r[i] = (r[i] || 0) + b;
        });
        return r
    }, []);
 })

However, this tells me that 'a.forEach is not a function', I must admit that I'm not sure exactly what the reduce function is doing, but I think perhaps that it isn't working because my arrays are not an array of arrays, they exist separately.

Javascript tells me they are objects, not arrays, but I'm not sure that is significant. Please could someone tell me how to do this?

bevc
  • 203
  • 3
  • 14

1 Answers1

1

The difference with the question you linked seems to be your numeric data, that is stored inside array of objects (in property yearsTotal) - and not in array of arrays of numbers.

If that's the case, you can just create another array storing only the values you need:

const projectYearsTotal = this.projects.map(p => p.yearsTotal);

... and then you can proceed with reduce-forEach-ing it.

Your current solution tries to 'zip-sum' the array of numbers (value of 'yearsTotal' of each individual project), not array of arrays of numbers. Hence forEach is not a function error.

raina77ow
  • 103,633
  • 15
  • 192
  • 229