Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Average in Javascript

Then I need a function that gets the average high. Here is what i did:

    function getAverageHeight() {
        let total_height = 0;
        let average_height = statues.length;

        if (statues.length > 0) {
            for (let i = 0; i < statues.length; i++) {
                let statue = statues[i];

                total_height += isNaN(statues.height) ? 0 : statue.height;
            }
        average_height = (total_height / statues.length).toFixed(2);
         }
       return average_height;
       } 

But when i test it i got NaN as as response not the average. What I did wrong here? Can someone give a clue?

like image 834
Erick Matt Avatar asked Mar 11 '20 20:03

Erick Matt


People also ask

How do you calculate average in JavaScript?

You calculate an average by adding all the elements and then dividing by the number of elements. var total = 0; for(var i = 0; i < grades. length; i++) { total += grades[i]; } var avg = total / grades.

How can I calculate average?

Average This is the arithmetic mean, and is calculated by adding a group of numbers and then dividing by the count of those numbers. For example, the average of 2, 3, 3, 5, 7, and 10 is 30 divided by 6, which is 5.

What is average array?

Given an array, the task is to find average of that array. Average is the sum of array elements divided by the number of elements. Examples : Input : arr[] = {1, 2, 3, 4, 5} Output : 3 Sum of the elements is 1+2+3+4+5 = 15 and total number of elements is 5.


2 Answers

A lot of the solutions here are pretty good, but there are edge cases with isNan like true and ''. It's safer to use parseInt first. Here's a solution that tosses out edge cases and returns the average.

let statues = [];
function createStatue(name, city, heightInMeters) {
  statues.push({
    name,
    city,
    heightInMeters
  });
}

// create statues + edge cases inputs
createStatue("Number", "New York", 46);
createStatue("Decimal", "Florence", 5.17);
createStatue("String", "Florence", '123');
createStatue("True", "Boston", true);
createStatue("Empty", "New York City", '');


function getAverageHeight() {
  // Filter out bad cases here
  const filteredStatues = statues.filter((x) => {
    let num = parseInt(x.heightInMeters);
    return !isNaN(num);
  });

  const total = filteredStatues.reduce((acc, x) => {
    return acc+parseInt(x.heightInMeters);
  }, 0);
  return (total/filteredStatues.length).toFixed(2);
}

console.log(getAverageHeight());

EDIT: The OP has provided the original code. Looking at it there are some oddities.

heightInMeters: heightInMeters,
  isLongerThan: function (other_statue) {            
    return this.highInMeters > other_statue.hightInMeters;

It looks like there are several typos here and the code shouldn't run.

like image 141
Joseph Cho Avatar answered Sep 30 '22 13:09

Joseph Cho


You want to be using

isNaN(statue.height)

Rather than

isNaN(statues.height)
like image 20
DougM Avatar answered Sep 30 '22 13:09

DougM