Home > Software engineering >  Pass array in another array of objects
Pass array in another array of objects

Time:10-30

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

CodePudding user response:

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 "%"}
    }))

CodePudding user response:

I suggest this method.

  const sumAndAvr = []
  
  arr.forEach((el) => {
      const subsumAndAvr = [];
      el.forEach(ele=>{
          let sum = 0;
    let avg=0;
    ele.map((el2) => {
        sum  = el2
       
    })
    avg=sum/ele.length
    subsumAndAvr.push({ total: sum, average: avg   "%" });
})
sumAndAvr.push(subsumAndAvr);
});

CodePudding user response:

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%
  ]
];

const result = arr.map((arrOfLists) => arrOfLists.map(list =>
  list.reduce((acc, num, index) => {
   const newTotal=(acc.total||0)   parseInt(num)
    return {
      average: newTotal / list.length,
      total: newTotal
    };
  }, { })))
console.log(result)

  • Related