Home > Enterprise >  How to perform operations on nested array of objects inside an array using javascript?
How to perform operations on nested array of objects inside an array using javascript?

Time:02-04

I am trying to calculate the average on nested array objects fields which is inside an another array. Here is the array I defined:

    let arr = [
[{"category":"behavioural", "rating":3}, {"category":"technical", "rating":4.5}],
[{"category":"behavioural", "rating":1}, {"category":"technical", "rating":2.5}],
[{"category":"behavioural", "rating":4}, {"category":"technical", "rating":2}]
]

I want to calculate the average of ratings in its respective category and store it in an object.

Expected output:

"metricsaverage" : {
    "behavioral" : 2.66,
    "technical" : 3
}

Where 2.66 and 3 is the average of all ratings with its respective category from the nested array of objects.

CodePudding user response:

working example here: https://jsfiddle.net/galeroy/ot1pkvqg/4/

  let arr = [
      [{"category":"behavioural", "rating":3}, {"category":"technical", "rating":4.5}],
      [{"category":"behavioural", "rating":1}, {"category":"technical", "rating":2.5}],
      [{"category":"behavioural", "rating":4}, {"category":"technical", "rating":2}]
    ]

    var behavioralTotal = 0,
        behavioralItems = 0,
        technicalTotal = 0,
        technicalItems = 0;

    arr.forEach(function(outerItem){         
      outerItem.forEach(function(innerItem){
        if(innerItem.category === 'behavioural'){
          behavioralTotal  = innerItem.rating;
          behavioralItems  ;
        }
        else if (innerItem.category === 'technical')
        {
          technicalTotal  = innerItem.rating;
          technicalItems  
        }
      })
    });

    console.log(
      'metricsaverage = { \n'  
        '"behavioral" : '   (behavioralTotal/behavioralItems).toFixed(2)   ',\n'  
        '"technical" : '   (technicalTotal/technicalItems).toFixed(2)   '\n'  
      '}'
    )

CodePudding user response:

Try this

const array = [[{"category":"behavioural", "rating":3}, {"category":"technical","rating":4.5}],[{"category":"behavioural", "rating":1}, {"category":"technical", "rating":2.5}],[{"category":"behavioural", "rating":4}, {"category":"technical", "rating":2}]];

let arrBeh = [];
let arrTech = [];

array.forEach( e => {
    arrBeh.push(e[0]["rating"]);
  arrTech.push(e[1]["rating"]);
})

calcAvg = (arr) => {
    const sum = arr.reduce((a, b) => a   b, 0);
    const avg = (sum / arr.length) || 0;
  
  console.log(avg)
}

calcAvg(arrBeh);
calcAvg(arrTech);

CodePudding user response:

The variable arr is referencing Array of Objects. I would iterate the array and retrieve the values as needed. So the syntax to iterate the array and get the rating value is: arr[i].rating where i is the counter variable.

  •  Tags:  
  • Related