CHALLENGE:
Complete the square sum function so that it squares each number passed into it and then sums the results together.
For example, for [1, 2, 2]
it should return 9
because 1^2 + 2^2 + 2^2 = 9
.
Let’s think through it together!
- Whenever you see a problem that is taking in an array, and you’re having to keep track of the end result, you should be hearing alarm bells about reduce().
- Reduce takes in a function and that function is going to have two key values: an accumulator and the current value. The accumulator in this case is our sum. We’ll be adding to the variable “sum”. The current value is going to be each of the numbers that we’re adding in our array.
- Reduce is going to loop through the array, I can do whatever I want with each number in the array, and in this case I’m squaring each number, and that’s the sum I’m keeping track of.
- Picture Mario jumping across the sky blocks and grabbing coins: the jump itself is the accumulator, and the current value is updated each time he lands on a block. Squaring each number is done inside the block.
FOLLOW THE PREP METHOD:
Parameters
- Array of numbers (positive only, no gotchas)
Returns
- The sum of the squares of each number provided in the array.
Examples
- [1, 2, 2] = 9 1^1 = 1, 2^2 = 4, 2^2 = 4, so total sums of squares is 9
- ([1,2,2,1]), 10)
- ([1,2,3]), 14)
Pseudocode
- First, create the function line: function sumSquares(arr)
- Next, setup console.log tests using provided examples
- What do we do now?
- We want to return the sum of the squares, and will need to keep track of the sum as we loop through the array.
- We’ll use the reduce() method, with two key values. A for accumulator, and C for current value.
- (Accumulator) + (Current Value * Current Value)
- 0 is placed to catch any errors from a possible empty array, ensuring that the output will be 0 and not “undefined”.
Solution
function sumSquares(arr){
return arr.reduce((a, c) => a + c*c, 0)
}
console.log(sumSquares([1,2,2]), 9)
console.log(sumSquares([1,2,2,1]), 10)
console.log(sumSquares([1,2,3]), 14)
FURTHER EXPLORATION:
- MDN, Reduce Text
- Reduce explained with Lego Bricks Text
- FreeCodeCamp Guide to the Reduce Method Text
- James Quick, Javascript Reduce Video
- Wes Bos JS30, at 8:58 Video
- Increment syntax – can you write this without looking?
- Arrow function – why is it best practice here? How and why is an arrow function used within another function?
- Why is the 0 important? because it catches a possible empty array and makes sure the answer is zero rather than undefined.