Taking the payload below, I need to output the average of each reading.
For example the readings for key 2 are 1, 4, 7. The average is (1+4+7)/3 = 4.
The data is formatted in multi-dimensional arrays, such that each sub-array contains pairs with a key and a reading value. For example:
[
[
[2, 1],
[4, 2],
[6, 3]
],
[
[2, 4],
[4, 5],
[6, 6]
],
[
[2, 7],
[4, 8],
[6, 9]
]
]
The final result should be:
[
[2, 4],
[4, 5],
[6, 6]
]
My effort so far seems to work.
const payload = [
[
[2, 1],
[4, 2],
[6, 3]
],
[
[2, 4],
[4, 5],
[6, 6]
],
[
[2, 7],
[4, 8],
[6, 9]
]
]
const result = payload.reduce((accumulator, currentValue, currentIndex, array) => {
if(currentIndex === 0){
return accumulator
}
return currentValue.reduce((a, c, i) => {
accumulator[i][1] += c[1]
return accumulator
}, accumulator)
}).map((currentValue, index, array) => {
return [currentValue[0], currentValue[1] / array.length]
})
payload.reduce(...)
mutates the first element ofpayload
- that is probably unexpected behavior and could cause bugs further on. \$\endgroup\$