The picture shown is a json file that stores the AQI data for the whole year of 2014. Now I want to calculate the monthly average AQI. How should I process this array?
黄舟2017-07-05 10:38:42
arr.reduce((r,v)=>r[v.date.split('/')[1]-1].push(v)&&r,new Array(12).fill(0).map(_=>[]))
This return result can return a new array containing 12 arrays, each sub-array contains the AQI data of the current month
I just found out that the main purpose of the poster is to find the average AQI every month, so you can do this:
arr.reduce((r,v)=>r[v.date.split('/')[1]-1].push(v)&&r,new Array(12).fill(0).map(_=>[]))
.map((i,k)=>{
let r = i.reduce((r,v)=>{for(let j in r)r[j]+=(+v[j]);return r},{beijing:0,shanghai:0,guangzhou:0});
for(let j in r) r[j] = parseInt(r[j]/i.length);
return {...r,month:k+1+'月'}
})
This result returns an array containing 12 items in the shape of {month:'January',beijing:12,shanghai:24,guangzhou:36}
, and the value inside is the average value of each month.
三叔2017-07-05 10:38:42
It feels like you don’t need to process the data, which will only continue to consume memory. You only need to know the starting point and ending point of each month, and just use the starting point and ending point to get the array for calculation.
Because in fact, the data It’s all here, it’s just that the rules for how you use the data are different
PHP中文网2017-07-05 10:38:42
Your question is mainly about how to divide into 12 groups. I provide two simple ideas
Convert date into date object and group by month
Use regular rules to get matching dates to group them
迷茫2017-07-05 10:38:42
From the analysis of the JSON
format you gave:
Peripheral array 1-12, representing 12 months
Traverse the array again to get object
, take the data
value of object
, divide it according to /
to get the month, and fill the object
into the corresponding month according to the month
Get the data corresponding to each month and process it on a monthly basis
滿天的星座2017-07-05 10:38:42
Let the back-end process the data grouping, and the front-end is responsible for using it.
巴扎黑2017-07-05 10:38:42
var jsonData = [{
'date': '2014/1/1',
'beijing': 80,
'shanghai': 123,
'guangzhou': 99
},{
'date': '2014/1/2',
'beijing': 80,
'shanghai': 123,
'guangzhou': 99
},{
'date': '2014/2/1',
'beijing': 80,
'shanghai': 123,
'guangzhou': 99
}];// 保存的json数据
var arr = [{'date': '1', 'b': 0, 's': 0, 'g': 0}];
var k = 0;
for(var i = 0; i < jsonData.length; i++) {
var item = jsonData[i];
var dateArr = item.date.split('/');
if (dateArr[1] == arr[k].date) {
arr[k].b += item.beijing;
arr[k].s += item.shanghai;
arr[k].g += item.guangzhou;
} else {
var param = {
'date': dateArr[1],
'b': 0,
's': 0,
'g': 0
};
k++;
arr.push(param);
}
}
console.log(arr);
The above code sums the data of each month. It should be simple to average. However, the above code has a requirement for json data, which is that all the data must be classified according to the month.