Search code examples
javascriptarraysloopsjavascript-objects

Reduce arrays in objects that in big array JS


I have a nested array, consisting of a lot of objects (400 items). That objects have an ID property and an incomes property. That incomes property is an array of objects (40 items) that have value and date.Question is, how can I iterate through that main array to sum all my small array values to one summary?

[{id: 1-400, incomes:[{value: "String", date: "String"}]}]

And, for example, that summary will be the 3rd property of main array:

[{id: 1-400, incomes:[{value: "String", date: "String"}], summaryIncome: "number"}]

I can iterate for that 400 items with for in loop, but I don`t understand how can I iterate both for big 400 items and small 40 items arrays with one loop.

 for(let i in data){
   data[i].incomes[i].value
}

So i will be >40 and I`ll get undefined in incomes[i].value. Please help :)


Solution

  • var a = [
      {id: 1, incomes: [{value:1}, {value: 2}]}, 
      {id: 2, incomes: [{value:2}, {value: 3}]}];
    
    var b = a.map(item => ({
      ...item,
      summaryIncome: item.incomes.reduce((t, income) =>
        t += income.value, 0)
    }));
    
    console.log(b);
    

    This should print:

    {id: 1, incomes: Array(2), summaryIncome: 3}
    {id: 2, incomes: Array(2), summaryIncome: 5}