gpt4 book ai didi

javascript - 如何过滤 json 并获取在 js 中创建线图的平均值?

转载 作者:行者123 更新时间:2023-11-30 19:14:09 26 4
gpt4 key购买 nike

我有 json 格式的数据,所以我想用 plotly js 绘图,我需要按学期创建不同州的图,所以我需要过滤每个州(例如加利福尼亚州),然后我需要得到每个学期的平均值,最后绘制它。

到目前为止我有这段代码,但我不知道如何在 js 中过滤 im new

// Trace1 
var trace1 = {
x: data.map(row => row.date),
y: data.map(row => row.snap_biannual_chan),
text: data.map(row => row.state_name),
name: "snap_biannual_chan",
type: "line"
};

// Combining both traces
var data = [trace1];

// Apply the group barmode to the layout
var layout = {
title: "Practice",
xaxis: {
categoryorder: "array",
}
};

// Render the plot to the div tag with id "plot"
Plotly.newPlot("plot", data, layout)

这是 json 示例:

“county_state_id”:“06001”, "pop_hispan_prop": ".1176472187212034", “pop_un_st”:3059000, "state_name": "加州", "county_name": "阿拉米达县", “pop_un_co”:109000, "state_id": "06", "county_id": "001", “pop_co”:1605217, “pop_st”:38654206, "state_abbrev": "CA", “学期”:“0118”, “快照受益人”:102034, “snap_biannual_chan”:-2.02980374083036, "sem": "18 月 18 日", “pop_un_co_per”:6.790359185082141, “pop_un_st_per”:7.913757173022776, “年”:2018年, “月”:1, "日期": "2018年1月"

最佳答案

您可以使用数组 filter()reduce() 方法来计算均值,而无需对一堆循环和变量进行微观管理。这是一个例子:

const data = [
{ state_id: "01", snap_biannual_chan: 5.5 },
{ state_id: "01", snap_biannual_chan: 3 },
{ state_id: "02", snap_biannual_chan: 5 }
];

const state01 = data.filter(x => x.state_id === "01");
const meanState01 = state01.reduce((acc, item) => {
acc.sum += item.snap_biannual_chan;
acc.mean = acc.sum / state01.length
return acc;
}, { sum: 0, mean: 0 });

console.log(meanState01);
console.log("the mean: ", meanState01.mean);

关于javascript - 如何过滤 json 并获取在 js 中创建线图的平均值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58174705/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com