Extensive use of Array’s Reduce family of functions makes Array processing silky and easy to look at and change. I don’t know friends can be checked on the MDN (JavaScript Array – | MDN (mozilla.org)
For example, to process the following data:
// Food and water every hour[{date: '2021-07-25'.hour: 0.food: 0.5.water: null },
{ date: '2021-07-25'.hour: 1.food: 1.5.water: null },
{ date: '2021-07-25'.hour: 2.food: 2.water: null},... {date: '2021-07-25'.hour: 22.food: 0.water: null },
{ date: '2021-07-25'.hour: 23.food: 0.water: null },
{ date: '2021-07-26'.hour: 0.food: 0.water: null },
{ date: '2021-07-26'.hour: 1.food: 0.water: null},...Copy the code
Demand is: count the meals this guy eats every day.
You can do this with the traditional for, but it’s mainly to illustrate the situation: aggregate each day and then calculate.
JS I haven’t figured out a way to group several elements from an Array using map/reduce/ Flat, etc. Become, become, become
[[{date: '2021-07-25'.hour: 0.food: 0.5.water: null }
{ date: '2021-07-25'.hour: 1.food: 0.5.water: null}... ] [{date: '2021-07-24'.hour: 0.food: 0.5.water: null }
{ date: '2021-07-24'.hour: 1.food: 0.5.water: null}... ] [{date: '2021-07-23'.hour: 0.food: 0.5.water: null }
{ date: '2021-07-23'.hour: 1.food: 0.5.water: null}... ] . ]Copy the code
So to aggregate each day, use a new array to absorb the old array. The switch to generate the array is shown above, and the code is shown below.
const result = Array.apply(null, {// group_size is 24 hours
length:Math.ceil(datas.length/group_size)
}).map(
(item,index) = >{
return datas.slice(index * group_size, (index+1)* group_size); })Copy the code
After that, the simplest statistics are done when a two-dimensional array is flattened using a flatMap.
result.flatMap(
items => items.reduce(
(accumulator,currentValue)=> accumulator+currentValue.rain
,0
)
)
Copy the code
The two pieces of code look better joined together