Skip to content
Advertisement

Pass array in another array of objects

I have this nested array which I am trying to sum the number in the last arrays individually

so it should return 400 for each array also trying to get the average of the total, for example if it is 400 then it is 100%, if 399 it will be 99.99%, the average needs to be from 100% and dynamic if that makes sense.

I been using javascript map method, but every time I map over the array it returns the same array level, I couldn’t access the last array.

arr.map(item => item.map(item2 => item2))

example in code:

const arr = [
  [
    [100, 100, 100, 100], // sum 400 -> average 100%
    [100, 100, 100, 100], // sum 400 -> average 100%
    [100, 100, 98, 100], // sum 398 -> average 99.99%
    [100, 100, 100, 100], // sum 400 -> average 100%
  ],
  [
    [100, 100, 100, 99], // sum 399 -> average 99.99%
    [100, 100, 100, 100], // sum 400 -> average 100%
    [100, 100, 100, 100], // sum 400 -> average 100%
    [100, 100, 100, 100], // sum 400 -> average 100%
  ]
];

the result should be something like this

 const arr = [
      [
        {total: 400, average: 100%},
        {total: 400, average: 100%},
        {total: 398, average: 99,99%}, 
        {total: 400, average: 100%},
      ],
      [
        {total: 399, average: 99,99%}, 
        {total: 400, average: 100%},
        {total: 400, average: 100%},
        {total: 400, average: 100%},   
      ]
    ];

I would really appreciate if someone can help

Advertisement

Answer

I would’ve done something like this

  let data = arr.map(section => section.map(row => {
      let tot = row.reduce((pv,cv) => pv+cv,0);
      return {'total':tot,'avg':tot/row.length+"%"}
    }))
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement