# Calculate the average of a key from an array of objects from parameter

#1

I have an array of objects of a shopping list and want to calcule the average of the “price” key. I shortened the list only to “name” and “price”, but I still have problems

``````const finalM = (prList) => {
let median = 0;
(for var i in prList) {
median += prList[i].price;
}
return median / prList.length;

const product = (ls) => {
for(var i in ls){
document.write("<h1> Product: " + ls[i].name + "</h1>");
document.write("<h1> Price: " + ls[i].price + "</h1>");
}
document.write("<h1> Median: " + mediaf(ls[i].price) + "</h1>");
}
``````

And I call the function in HTML with these values

``````product([
{"name": "Apple", "price": 3},
{"nome": "Banana", "price": 5}
]);
``````

#2

This should work:

``````const average = (prList) => {
let sum = 0;
for (var i in prList) {
sum += prList[i].price;
}

return sum / prList.length;
}

const product = (ls) => {
for (var i in ls) {
document.write("<h1> Product: " + ls[i].name + "</h1>");
document.write("<h1> Price: " + ls[i].price + "</h1>");
}
document.write("<h1> Average price: " + average(ls) + "</h1>");
}
``````

P.S. Please don’t confuse average with median, they are completely different things.

#3

Oh, sorry, thanks for the advice and thanks for helping me ! I’ve been looking for quite some time.