Skip to content

Commit 293a131

Browse files
committed
[EX-11.6/st-compl] finding-average-value
Finding "average" of num's in arr. Only by reduce(). Worth noting: - alternative solutions (best practice). FS-dev: B-3 / JS basic
1 parent bced09c commit 293a131

1 file changed

Lines changed: 19 additions & 0 deletions

File tree

  • full-stack-dev/3-js-basic/11-arrays-iterations/11-6-ex-finding-average-value
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
// Нужно найти "среднее значение" чисел произвольного массива, с помощью reduce().
2+
3+
const arr = [1, 4, 4, 10];
4+
5+
const meanValue = arr.reduce((acc, num) => acc + num / arr.length, 0);
6+
console.log(meanValue); // 4.75
7+
8+
// ?? альтернативное решение
9+
const newMeanValue = arr.reduce((acc, num, index, array) => {
10+
acc += num;
11+
12+
if (index === array.length - 1) {
13+
return acc / array.length;
14+
}
15+
16+
return acc;
17+
}, 0);
18+
19+
console.log(newMeanValue); // 4.75

0 commit comments

Comments
 (0)