Hello everyone I’m stuck on an exercise I set myself.
I have several objects. Each of its objects contain an array that contain numbers related to the array index.
What I’m trying to do is to get, for example, an array that would return to me the average of each array’s index.
For example in my new table at index 0 I would have 4+7/2 , at index 1 I would have 5+6/2.
object1 = {
"numbers": [{
"number": 4,
}, {
"number": 5,
}
]
}
object2 = {
"numbers": [{
"number": 7,
}, {
"number": 6,
}
]
}
My first idea was to go on a reduce() but I did not find my account.
Could you guide me?
Thanks in advance.
I would like to know if this is possible for several objects (object1 ,object2 , object3 ….) and also for more than two data in my tables "numbers"
2
Answers
You could use the numbers array’s indexes to reduce all arrays:
Another alternative and efficient approach will be to calculate the averages. Instead of mapping over the transformed data twice, You can use a single loop to iterate through the objects and numbers to accumulate the sum and count for each index and then get the averages.
Refer the code below :