use reduce to calculate the average [closed]

-4

I have the following "data" that is inside an object array and I have to find the average of each value of the "data"

this is the object I'm working with

   var MARKDATA = {
    "SOR": {
      "mark": [
      {
       "data": {
        "2015": 21.680000,
        "2016": "",
        "2017": 23.760000
       },
      "markName": "swimming",
      "markCode": "SWM"
     },
     {
      "data": {
       "2015": "",
       "2016": 61.55429840,
       "2017": 61.482299804
      },
     "markName": "running (time)",
     "markCode": "RM"
    }
   ]
  } 
};

I want to create a new array with the average of the data values using reduce or any method that helps me with this. thanks

    
asked by c.chester 05.01.2019 в 17:31
source

1 answer

1

I understand your question in the following way: you need the average of the values that are reflected in data and store them in a new array.

In your code you put markCode: SWM and markCode: RM , then I'm assuming you want the averages by brand.

Because putting them directly in an array makes the clarity of who each average belongs to a bit less, I have decided to put them in a Object , then you can work with that object if you need a specific average or all regardless of the brand .

Let's start:

// Aqui tienes tu obejto inicial
// (Acostumbro a usar ES6)

const MARKDATA = {
    "SOR": {
      "mark": [
      {
       "data": {
        "2015": 21.680000,
        "2016": "",
        "2017": 23.760000
       },
      "markName": "swimming",
      "markCode": "SWM"
     },
     {
      "data": {
       "2015": "",
       "2016": 61.55429840,
       "2017": 61.482299804
      },
     "markName": "running (time)",
     "markCode": "RM"
    }
   ]
  } 
};

// En el siguiente objeto almacenaremos la información
// de marca, los datos y el promedio.

let dataByMark = {};

// El siguiente bloque trabaja sobre la estructura
// del objeto MARKDATA que has dado como ejemplo.

for (let idx in MARKDATA.SOR.mark) {
    // La clave 'mark' almacena un array con la data
    // Cada elemento del array es un objeto
    // Por cada elemento del array crearemos un objeto
    // que contenga la data y el promedio
    
    // Aqui guardamos el codigo de marca
    let markCode = MARKDATA.SOR.mark[idx].markCode;
    
    // Aqui declaramos un nuevo objeto que va a
    // contener la data y el promedio
    let markData = { 
        data: [],
        prom: []}

    // Ahora accedemos a los datos del objeto
    for (let key in MARKDATA.SOR.mark[idx].data) {
    // Guardamos la data en el objeto 'markData' en la clave 'data'
        markData.data.push(Number(MARKDATA.SOR.mark[idx].data[key]));
    // Si te fijas uso la función Number(), ya que en
    // la data original veo campos string vacíos
    // (""), al pasarlos a Number me aseguro que
    // el cálculo de promedios sea correcto
    // Cada string vacío se hace cero al aplicarle
    // la función Number. Que es lo deseado.
    
    // No obstante es bueno capturar ese tipo de errores antes de realizar cálculos
    // Si tratamos de pasar un string a Number(), el resultado será NaN.
    }
    
    // Aqui calculamos el promedio de los datos obtenidos
    //Lo almacenamos en nuestro objeto 'markData' en la clave 'prom'
    markData.prom = markData.data.reduce(function(a, b, c) { return ((a + b)/c); });
    
    // Por último, en cada iteración almacenamos nuestro
    // objeto 'markData' en el objeto 'dataByMark'
    dataByMark[markCode] = markData;
}

// Ahora toda la información que necesitamos estará en nuestro objeto dataByMark

// Si necesitamos los promedios en un nuevo 'array'
// sin importar la marca lo hacemos desde nuestro 
// objeto dataByMark

let promedios = [];

for (let mark in dataByMark) {
    console.log('mark: ', mark, ' prom: ', dataByMark[mark].prom);
    promedios.push(dataByMark[mark].prom);
}

// Ahora ya tienes los promedios en un nuevo array

console.log('promedios: ', promedios);

I hope this helps you, and do not hesitate to ask again if you have any new questions or if something is not clear to you.

    
answered by 05.01.2019 / 19:39
source