獲取具有對像一鍵值的數組的平均值 - Javascript (Get the avarage value of array with objects one key value - Javascript)


問題描述

獲取具有對像一鍵值的數組的平均值 ‑ 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 HovhannisyanFullstack Guy)

參考文件

  1. Get the avarage value of array with objects one key value ‑ Javascript (CC BY‑SA 2.5/3.0/4.0)

#reduce #javascript #object #arrays






相關問題

Lapack 的行縮減 (Lapack's row reduction)

泡菜cython類 (pickle cython class)

將列表列表減少為字典,以子列表大小為鍵,出現次數為值 (Reduce list of list to dictionary with sublist size as keys and number of occurances as value)

使用 map/reduce 在列表中添加一對數字的差異 (Adding difference of pair of numbers in list using map/reduce)

Python 2.7:使用 reduce 驗證元素是否在列表中 (Python 2.7: Using reduce to verify that elements are in a list)

使用 map/reduce 計算總數 (Using map/reduce to calculate totals)

Swift reduce - 為什麼 value 是可選的? (Swift reduce - why is value optional?)

獲取具有對像一鍵值的數組的平均值 - Javascript (Get the avarage value of array with objects one key value - Javascript)

如何將數據數組轉換為在顫振/飛鏢中展開或折疊的小部件列表? (How to convert an array of data to a list of widgets with expand or fold in flutter/dart?)

樹的字符串路徑 (JavaScript) (String-path to Tree (JavaScript))

如何重命名對像數組中對象的所有鍵? (How does one rename all of an object's keys within an array of objects?)

使用reduce轉換一個js對象 (transform a js object using reduce)







留言討論