【发布时间】:2021-09-26 10:16:20
【问题描述】:
您好,我有一个如下所示的数组:
[
{
group: "23",
delays: [
{ Station: "a", Arrival: "3", Departure: 0 },
{ Station: "b", Arrival: -179, Departure: 0 },
{ Station: "c", Arrival: -156, Departure: 0 },
],
},
{
group: "23",
delays: [
{ Station: "a", Arrival: "5", Departure: 79 },
{ Station: "b", Arrival: 0, Departure: 0 },
{ Station: "c", Arrival: 68, Departure: 68 },
],
},
];
到目前为止,我已经能够消除重复项并将变量相加......但是我希望获得这些值的平均值而不是求和它们。 这是总结它们的代码,合并“计算平均值”功能的最佳方法是什么?假设 Station b 出现两次,那么我会将 Station b 的总和除以 2。
var dataPoints = [];
var xs = [];
var n = [];
function addData(data) {
for (var i = 0; i < data.length; i++) {
for (var j = 0; j < data[i].delays.length; j++) {
dataPoints.push({
x: data[i].delays[j].Station,
y: data[i].delays[j].Arrival
});
}
}
values = ["no information"]
dataPoints = dataPoints.filter(item => !values.includes(item.y));
dataPoints.forEach((e) => {
if (!xs.includes(e.x)) { n.push(e); xs.push(e.x) }
else { n.forEach(f => f.y += f.x == e.x ? e.y : 0) }
// make a change here to get average of duplicate stations
// Say Station b appears twice, then I would divide sum of
// Station b by two.
})
console.log(n)
【问题讨论】:
-
想要的结果是什么?
-
我希望得到平均值,而不是对数组中的 y 值求和
-
ez 回答:
You calculate an average by adding all the elements and then dividing by the number of elements. -
@luthienaerendell 在问题本身中添加预期代码
-
@johnSmith 所以我必须添加一个计数器变量是吗?还是我除以 array.length 对不起,我对 javascript 很陌生
标签: javascript jquery arrays json