Reputation: 29
I am working on an angular app. I have an array as follow:
data = [
{
num1:12.233,
num2: 13.345
},
{
num1:10.233,
num2: 23.345
},
{
num1:18.233,
num2: 33.345
}
]
Similarly at runtime time I can have many elements. I want to traverse array such that I can add all the num1 and divide them by number of num1 present. For example, I want to write a code which can take num1 from every element
12.233 + 10.233 + 18.233 / 3(total num1 elements in array)
Similarly for num2.
How can I do that?
Upvotes: 0
Views: 75
Reputation: 781
let avg = data.reduce( (accumVariable, curValue) => accumVariable + curValue.num1 , 0 ) / data.length
Upvotes: -1
Reputation: 25408
You can simply use reduce
to get the total of elements and then divide it with data.length
const data = [
{
num1: 12.233,
num2: 13.345,
},
{
num1: 10.233,
num2: 23.345,
},
{
num1: 18.233,
num2: 33.345,
},
];
const avg = data.reduce((acc, curr) => acc + curr.num1, 0) / data.length;
console.log(avg);
For average of num2
then you can similarly do as:
const avg = data.reduce((acc, curr) => acc + curr.num2, 0) / data.length;
You can also get the average
using a single iteration
as:
const data = [
{
num1: 12.233,
num2: 13.345,
},
{
num1: 10.233,
num2: 23.345,
},
{
num1: 18.233,
num2: 33.345,
},
];
const [avgNum1, avgNum2] = data
.reduce((acc, curr) => [acc[0] + curr.num1, acc[1] + curr.num2], [0, 0])
.map((n) => n / data.length);
console.log(avgNum1, avgNum2);
Upvotes: 5
Reputation: 665
You can loop through data
and add the values of num1
and num2
to a variable, then divide it by the length of data
(which is 3).
const data = [
{
num1: 12.233,
num2: 13.345
},
{
num1: 10.233,
num2: 23.345
},
{
num1: 18.233,
num2: 33.345
}
]
let num1 = 0;
let num2 = 0;
for (let i = 0; i < data.length; i++) {
num1 += data[i].num1;
num2 += data[i].num2;
}
const num1Avg = num1 / data.length;
const num2Avg = num2 / data.length;
console.log(`Average of num1: ${num1Avg}`)
console.log(`Average of num2: ${num2Avg}`)
Upvotes: 0