javascript - 通过过滤未定义计算对象数组的平均值

标签 javascript node.js arrays object

我正在尝试计算对象数组中具有相同键值的平均值。 并非所有对象都包含与另一个相同的值,但我仍然希望根据它在数组中出现的次数返回平均值。 比如我要

const Object1 = [{
  2005: 5.6,
  2006: 5.2
}, {
  2005: 5.6,
  2006: 5.7,
  2007: 5.4
}, {
  2005: 5.6,
  2006: 5.9,
  2007: 5.8
}]

返回

{
  2005: 5.599999999999999,
  2006: 5.6000000000000005,
  2007: 5.6
}

到目前为止,这是我尝试过的。 现在的问题是我无法按它出现的次数来/它。如果缺少年份,则该值将变为未定义,这会导致结果为 NaN。

const Object1 = [{
  2005: 5.6,
  2006: 5.2
}, {
  2005: 5.6,
  2006: 5.7,
  2007: 5.4
}, {
  2005: 5.6,
  2006: 5.9,
  2007: 5.8
}]
const years = Object.keys(Object.assign({}, ...Object1));
const Result = years.reduce((a, v) => ({
  ...a,
  [v]: v
}), {})
console.log(Result)
years.map((year) => {

  const value =
    Object1.map(function(obj) {
      return obj[year]
    }).reduce(function(a, b) {
      return (a + b)
    }) / years.length
  Result[year] = value
})
console.log(Result)

最佳答案

您可以按年对分数进行分组,并单独根据每个组计算分数

const object1 = [
  {
    2005: 5.6,
    2006: 5.2,
  },
  {
    2005: 5.6,
    2006: 5.7,
    2007: 5.4,
  },
  {
    2005: 5.6,
    2006: 5.9,
    2007: 5.8,
  },
];

const groupPointByYears = object1.reduce((map, obj) => {
  for (const [year, point] of Object.entries(obj)) {
    if (!map.has(year)) {
      map.set(year, []);
    }
    map.get(year).push(point);
  }

  return map;
}, new Map());

console.log(Array.from(groupPointByYears));

const res = Object.fromEntries(
  Array.from(groupPointByYears).map(([year, points]) => [
    year,
    points.reduce((sum, point) => sum + point, 0) / points.length,
  ])
);

console.log(res);

关于javascript - 通过过滤未定义计算对象数组的平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71948451/

相关文章:

javascript - 使用 node.js 编辑和创建 HTML 内容

android - 在 Android 和 Node.js 之间传输大文件

node.js - Node 串口 O/S 要求

php - 如何获取数组范围

javascript - 悬停图像功能 : how can I set its dimension by percentage and how to simplify this code?

javascript - ng-true-value ='0' 选取错误的值

Java Arraylist 存储用户输入

ruby - ruby 中的增量数组,0..40,[10、20、30、40]

javascript - 想了解如何调用此 JavaScript 函数?

javascript - 如何从 h :selectManyMenu 获取值