Average in Javascript

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.


You want to be using

isNaN(statue.height)

Rather than

isNaN(statues.height)