首页 > 解决方案 > 查找对象数组中每个索引的平均值?

问题描述

我的大脑正在融化……我正在努力完成以下工作:

我有一个对象数组,其中也有数组:

const data = [
  {
    seatChartResults: {
     '10th': [40, 40, 40, 39, 39, 38, 38, 38, 38, 38],
     '90th': [44, 44, 44, 45, 45, 46, 46, 46, 47, 47],
      avg: [42, 42, 42, 42, 42, 42, 42, 42, 42, 42],
    }
  },
  {
    seatChartResults: {
     '10th': [41, 40, 40, 39, 39, 39, 38, 38, 38, 38],
     '90th': [43, 44, 45, 45, 45, 46, 46, 46, 47, 47],
      avg: [42, 42, 42, 42, 42, 42, 42, 42, 42, 42],
    }
  },
]

现在我想实现一些能够获得这些键的每个索引的平均值的东西,例如:

(data[0].seatChartResults['10th'][0] + data[1].seatChartResults['10th'][0]) / 2

等等 ...

最终结果是将对象聚合到相同的结构中:

  { // With all averages aggregated
    seatChartResults: {
     '10th': [41, 40, 40, 39, 39, 39, 38, 38, 38, 38],
     '90th': [43, 44, 45, 45, 45, 46, 46, 46, 47, 47],
      avg: [42, 42, 42, 42, 42, 42, 42, 42, 42, 42],
    }
  },

这就是我现在所拥有的:

const avgSeatChartResults = (allLambdas) => {

  return allLambdas.reduce((acc, { seatChartResults }) => {

    Object.keys(seatChartResults).forEach(key => {

      const allKeys = [acc.seatChartResults[key] = seatChartResults[key]]

      allKeys.map(item => item.reduce((acc, currValue) => acc + currValue, 0) / item.length )      

    })

    return acc

  }, { seatChartResults: {} })

}

但是...我不确定这样做是否正确。请帮忙。

标签: javascriptnode.jslodash

解决方案


您可以用来执行此操作的一种方法是:

  • 首先计算相应数组的总和并将其收集在地图中(或对象,如果您愿意的话)
  • 然后通过计算每个数组中每个条目的平均值进一步将其减少到所需的对象

const data = [{
    seatChartResults: {
      '10th': [40, 40, 40, 39, 39, 38, 38, 38, 38, 38],
      '90th': [44, 44, 44, 45, 45, 46, 46, 46, 47, 47],
      'avg': [42, 42, 42, 42, 42, 42, 42, 42, 42, 42],
    }
  },
  {
    seatChartResults: {
      '10th': [41, 40, 40, 39, 39, 39, 38, 38, 38, 38],
      '90th': [43, 44, 45, 45, 45, 46, 46, 46, 47, 47],
      'avg': [42, 42, 42, 42, 42, 42, 42, 42, 42, 42],
    }
  },
];

const res = Array.from(data.reduce((acc, {seatChartResults}) => { // add corrsponding array entries
      Object.entries(seatChartResults).forEach(([k, arr]) => {
        acc.set(k, arr.map((n, i) => ((acc.get(k) || [])[i] || 0) + n));
      });
      return acc;
    }, new Map()).entries())
    .reduce((acc, [k, arr]) => { // compute average
      acc.seatChartResults[k] = arr.map(n => n / data.length);
      return acc;
    }, {seatChartResults: {}});

console.log(res);


推荐阅读