Многие решения здесь довольно хороши, но есть крайние случаи с isNan
, такие как true
и ''
. Сначала безопаснее использовать parseInt
. Вот решение, которое отбрасывает крайние случаи и возвращает среднее.
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());
РЕДАКТИРОВАТЬ: OP предоставил исходный код. Глядя на это, есть некоторые странности.
heightInMeters: heightInMeters,
isLongerThan: function (other_statue) {
return this.highInMeters > other_statue.hightInMeters;
Похоже, здесь несколько опечаток, и код не должен запускаться.