Dynamically calculate the average for a nested collection using lodash

前端 未结 4 537
予麋鹿
予麋鹿 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:36

    You can merge the objects using the spread syntax and lodash's _.mergeWith(). When merging, if the 2nd parameter (b) is a number divide it by the number of items in the original array to get it's respective contribution to the total average. If the 1st parameter (a) is a number, just add it without dividing (to avoid dividing the sum multiple times), or add 0 if it's undefined.

    I've added examples of 2 objects array, and 3 objects array.

    const getAvg = (data) => _.mergeWith({}, ...data, (a, b) => {
      if(_.isNumber(b)) {
        return ((b || 0) / data.length) + (_.isNumber(a) ? (a || 0) : 0);
      }
    });
    
    const data1 = [
    {"x":{"x1":1},"y":{"yt":0,"zt":4,"qa":3,"ft":0}},
    {"x":{"x1":5},"y":{"yt":10,"zt":2,"qa":0,"ft":0}}
    ];
    
    const data2 = [
    {"x":{"x1":1},"y":{"yt":0,"zt":4,"qa":3,"ft":0}},
    {"x":{"x1":5},"y":{"yt":10,"zt":2,"qa":0,"ft":0}},
    {"x":{"x1":3},"y":{"yt":2,"zt":6,"qa":3,"ft":0}}
    ];
    
    const result1 = getAvg(data1);
    
    console.log('2 objects in the array: ', result1);
    
    const result2 = getAvg(data2);
    
    console.log('3 objects in the array: ', result2);

提交回复
热议问题