1

## js計算object平均 並轉換成 integer

https://codepen.io/yztracker/pen/abbqJRj?editors=1111

``````const data  =[{"post":{"point":[5]},"avg":5},{"post":{"point":[6,1,3]},"avg":3.33}]
``````

### 2 個回答

2
dragonH
iT邦超人 5 級 ‧ 2019-11-04 20:29:21

dragonH

dragonH iT邦超人 5 級 ‧ 2019-11-04 20:46:34 檢舉

codepen

dragonH

``````      value=[{avg:2},{avg:3}]
let popularitySum = 0;
const len = value.length;
let item = null;
for (let i = 0; i < len; i++) {
item = value[i];

popularitySum = item.avg + popularitySum;

}
const averagePopularity = popularitySum /len ;
avgN=averagePopularity.toFixed(1)
console.log(avgN)
``````

dragonH iT邦超人 5 級 ‧ 2019-11-04 21:07:39 檢舉

froce iT邦大師 1 級 ‧ 2019-11-04 21:53:07 檢舉

dragonH iT邦超人 5 級 ‧ 2019-11-04 21:57:01 檢舉

froce iT邦大師 1 級 ‧ 2019-11-04 21:59:26 檢舉

dragonH iT邦超人 5 級 ‧ 2019-11-04 22:04:51 檢舉

2
froce
iT邦大師 1 級 ‧ 2019-11-04 21:35:09
``````const data  =[{"post":{"point":[5]},"avg":5},{"post":{"point":[6,1,3]},"avg":3.33}]

const result = data.map(item => item.post.point).flat()
const avg = result.reduce((cur, pre) => cur+pre, 0)/ result.length
``````

``````const result = data.map(item => item.post.point).reduce((cur,pre) => cur.concat(pre), [])
const avg = result.reduce((cur, pre) => cur+pre, 0)/ result.length
``````