Square(n) Sum

Square(n) Sum

Square(n) Sum

Katie Marie - Among the Branches's photo
Katie Marie - Among the Branches
·Jan 23, 2022·

3 min read

CHALLENGE

Square(n) Sum

Instructions: Complete the square sum function so that it squares each number passed into it and then sums the results together.

We start with the PREP method. Need a refresher? Check out this post.

Parameters

Array of numbers (positive only, no gotchas)

Returns

The sum of the squares of each number provided in the array.

Three Examples:

  1. [1, 2, 2] = 9 (explained: 1^1 = 1, 2^2 = 4, 2^2 = 4, so total sums of squares is 9)
  2. ([1,2,2,1]), 10)
  3. ([1,2,3]), 14)

Pseudocode

  1. First, get your outline on the blank page:
    • Create the function line: function sumSquares(arr)
    • Next, setup console.log tests

Talk through the tests - confirm that they're accurate and that they test for everything given in the examples.

  1. We want to return the sum of the squares, and will need to keep track of the sum as we loop through the array. (This language gives you a big fat hint - try looking at the methods at the MDN, and see if you can find one to use before reading further!)

    • We’ll use the reduce() method, with two key values. a stands for accumulator, and c for current value.
    • (Accumulator) + (Current Value * Current Value)
    • 0 is placed to catch any errors from a possible empty array, assuring 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)

NOTES

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. So we would have had this variable “sum” that we’re adding to. 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 that number, and in this case I’m adding it to accumulation, and that’s the sum I’m keeping track of. Whenever you see an array, and the problem is taking in an array, and you’re having to keep track of the end result… should be alarm bells about reduce().

Why is the 0 important? because it catches a possible empty array and makes sure the answer is zero rather than undefined.

ADDITIONAL RESOURCES:

WHAT DO I NEED TO REVIEW? WHERE DID I GET STUCK?

What is Increment syntax? Arrow function - why is it best practice here? How and why is an arrow function used within another function?

REMEMBER:

Explain every little thing Keep talking. It'll help you work out where you're stuck, and help you prepare for interviews!

 
Share this