I need help with my React Native app. I need to calculate the average value between each element of the array. The logic is as follows, if there are 4 elements with values 3,5,6,9, then you need to calculate the average value between 3 and 5 and divide by 1, between 3, 5, 6 and divide by 2, etc. The first value is counted as the initial value, so it is not taken into account.
I would appreciate any help.
return (
<View style={Styles.sectionContainer}>
{readings.map(
({
id,
date,
volume,
}) => {
return (
<View key={id} style={Styles.card}>
<Text
style={[
Styles.sectionHeading,
Styles.darkAppText,
{ fontWeight: "bold" },
]}
>
average: {average}
</Text>
</View>
);
}
)}
</View>
);
}
I was trying to do this inside map function, but it gives average between 2 last elements:
if (id == 1) {
average = 0;
} else if (id > 1) {
for (i = 1; i < readings.length; i++) {
average = (readings[i].volume readings[i - 1].volume) / i;
}
}
2
Answers
The below functions compute the average values according to what you’ve described and returns them as an
Array
:Your problem has nothing to do with React Native rather its simply a JS job.here is the code
Example usage: