Dynamically calculate the average for a nested collection using lodash

前端 未结 4 568
予麋鹿
予麋鹿 2021-01-27 17:03

I have a JSON array of objects (a collection) like:

[{
  \"x\": {
        \"x1\": 1
  },
  \"y\": {
    \"yt\": 0,
    \"zt\": 4,
    \"qa\": 3,
    \"ft\": 0,
          


        
4条回答
  •  心在旅途
    2021-01-27 17:23

    let objectArray = [{
      "x": {
            "x1": 1
      },
      "y": {
        "yt": 0,
        "zt": 4,
        "qa": 3,
        "ft": 0,
      }
    },
    {
      "x": {
            "x1": 5
      },
      "y": {
        "yt": 10,
        "zt": 2,
        "qa": 0,
        "ft": 0,
      }
    }];
    
    function findAverage(array) {
      
      let counter = {},
        result = {},
        i,
        obj,
        key,
        subKey;
      
      // Iterate through array
      for (i = 0; i < array.length; i++) {
        obj = array[i];
        // Copy each key in array element to counter object
        for (key in obj) {
          counter[key] = counter[key] || {};
          // Increment and keep count of key-values of counter based on values in array element
          for (subKey in obj[key]) {
            counter[key][subKey] = counter[key][subKey] || {total: 0, numElements: 0};
            counter[key][subKey].total += obj[key][subKey];
            counter[key][subKey].numElements += 1;
          }
        }
      }
      // Go back through counter to find average of all existing subkeys (based on incremented total and the number of elements recorded) and throw it into result object
      for (key in counter) {
        result[key] = result[key] || {};
        
        for (subKey in counter[key]) {
          result[key][subKey] = counter[key][subKey].total / counter[key][subKey].numElements;
        }
      }
      
      return result;
    }
    
    console.log(findAverage(objectArray));

    Not designed to be absolutely optimal, and copying objects can be done recursively without knowing in advance their structure, but I wanted to keep the steps as clear as possible.

    Edited to allow testing as snippet. Had no idea you could even do that on SO!

提交回复
热议问题