問題描述
獲取具有對像一鍵值的數組的平均值 ‑ Javascript (Get the avarage value of array with objects one key value ‑ Javascript)
我有一組有年齡的用戶,我想得到用戶的平均年齡。到目前為止,我嘗試使用 reduce
來實現它,但它不會實現它不是 reduce
的正確語法。
這是我的代碼:
let sam = { name: "Sam", age: 21 };
let hannah = { name: "Hannah", age: 33 };
let alex = { name: "Alex", age: 24 };
let users = [ sam, hannah, alex ];
function getAverageAge(array){
let sumAge = array.age.reduce(function(sum, current) {
return sum + current;
}, 0)
return (sumAge / (array.length + 1));
}
console.log( getAverageAge(users) ); // 21 + 33 + 24 / 3 = 26
在這種情況下,它應該返回 26。
參考解法
方法 1:
Arrays don't have a age
property it is your object that has it:
let sam = { name: "Sam", age: 21 };
let hannah = { name: "Hannah", age: 33 };
let alex = { name: "Alex", age: 24 };
let users = [ sam, hannah, alex ];
function getAverageAge(array){
const sumAge = array.reduce(function(sum, current) {
return sum + current.age;
}, 0)
return (sumAge / array.length);
}
console.log( getAverageAge(users) );
(by Robert Hovhannisyan、Fullstack Guy)