Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

149
Views
calculating average of elements in an array

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?

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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);

about 4 years ago · Juan Pablo Isaza Report

0

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}`)

about 4 years ago · Juan Pablo Isaza Report

0

let avg = data.reduce( (accumVariable, curValue) => accumVariable + curValue.num1 , 0 ) / data.length

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!