Ezra Butler
Ezra Butler

Reputation: 140

How do I create an Observable array which is the result of averaging mapped arrays

I am trying to figure out the hourly average of this collection called meterdata where each document in the collection has an array called hourlyarray which has a length of 24.

This code snippet maps the [0] all of the hourlyarrays and averages them together in a single number.

It wrote works perfectly, but only averages the first position. Is there a simple way to programmatically create an Observable on my component.ts to run this 24 times and then to batch all the results together in a single array?

this.avg0 = collectionRef.collection('meterdata', 
ref=> ref.where("day", "==", day )).valueChanges()
.pipe((map(data => data.map(d => d.hourlyarray[0])
.reduce((acc, avg) => acc + avg, 0)/data.length)));

Related: Is it not intelligent to be doing this calculation on the client side?

Upvotes: 2

Views: 68

Answers (1)

Zazaeil
Zazaeil

Reputation: 4119

.pipe(switchMap(data => from(data)), map(arrayofdata => arrayofdata.reduce(...))) should work if I understood your intention correctly. In short, it would covert your hourlyarray to an Observable and apply reduction among all the elements in that array.

Upvotes: 1

Related Questions