From 6bba0f099036c8c161aa0e72a3cde52911c400a1 Mon Sep 17 00:00:00 2001 From: Isabelle Viktoria Maciohsek Date: Fri, 9 Oct 2020 09:09:31 +0300 Subject: [PATCH] Update weightedAverage.md --- snippets/weightedAverage.md | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/snippets/weightedAverage.md b/snippets/weightedAverage.md index 750fc8292..03bdc0816 100644 --- a/snippets/weightedAverage.md +++ b/snippets/weightedAverage.md @@ -1,17 +1,27 @@ --- title: weightedAverage -tags: math,array,beginner +tags: math,array,intermediate --- Returns the weighted average of two or more numbers. -- Use `Array.prototype.reduce()` to add each value to an accumulator, initialized with a value of `0` and divide by the `length` of the array. +- Use `Array.prototype.reduce()` to create the weighted sum of the values and the sum of the weights. +- Divide them with each other to get the weighted average. ```js -const weightedAverage = (nums, weights) => - nums.reduce((acc, n, i) => acc + (weights[i] * n), 0) / nums.length; +const weightedAverage = (nums, weights) => { + const [sum, weightSum] = weights.reduce( + (acc, w, i) => { + acc[0] = acc[0] + nums[i] * w; + acc[1] = acc[1] + w; + return acc; + }, + [0, 0] + ); + return sum / weightSum; +}; ``` ```js -weightedAverage([1, 2, 3], [0.6,0.2,0.3]); // 0.6333 +weightedAverage([1, 2, 3], [0.6,0.2,0.3]); // 1.72727 ```