Search code examples
javascriptarraysjavascript-objects

javascript exclude some values in average calc


Here are some data:

data = [
 {"Age":26,"Level":8},
 {"Age":37,"Level":9},
 {"Age":null,"Level":15},
 {"Age":null,"Level":45}
];

from which I'm trying to calculate average for their properties:

var avg = {};
  var rows = data.length;
  data.forEach(obj => {
      Object.keys(obj).forEach(k => {
        if(obj[k] != null){
          avg[k] = (avg[k] || 0) + obj[k] / rows;
        }
      });
    });

  return avg;

but the problem is in items that has properties with null values, where I'm trying to exclude null values from the calculation, and if you take a look at the the codepen there is Age: 15.75 instead of 31.5 because length of the data is always 4 (and should be 2 since 2 of them are null). How would be the best way to get the length to not be including the nulls?


Solution

  • You could store the sum and count for every key independently.

    var data = [{ "Age": 26, "Level": 8 }, { "Age": 37, "Level": 9 }, { "Age": null, "Level": 15 }, { "Age": null, "Level": 45 }],
        avg = {},
        temp = {};
    
    data.forEach(obj => Object.keys(obj).forEach(k => {
        if (obj[k] === null) return;
        temp[k] = temp[k] || { sum: 0, count: 0 };
        temp[k].sum += obj[k];
        temp[k].count++;
        avg[k] = temp[k].sum / temp[k].count;
    }));
    
    console.log(avg);
    console.log(temp);
    .as-console-wrapper { max-height: 100% !important; top: 0; }