Code Wars - Sum(n)Strings

Breaking down code war challenges in a simple and understandable way.

The Problem Statement

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.

Analysis -Breaking down the question

Since it’s an array and we need to square each element - the map function will be perfect.

Next, we can use reduce function to sum the squared array.

Let’s see the solution in action.

The Syntax for solving the problem

The Map Function

map((element)=> {//your code here})  //map function returns 
//the new array without modifying the original array

The Reduce Function

reduce((previousValue, currentValue))=> {//Your code here } reduce function reduces 
//the entire array to a single value.

The Solution

Let’s write a basic function that takes an array as input as below

function squareSum(numbers){

}

Now, use the map function to square each element of the array.

function squareSum(numbers){
 const squared = numbers.map((number)=> Math.pow(number, 2)) //[1,4,6]
//At this point, it takes each
//element and squares using the Math.pow
return squared; 

}
squareSum([1,2,3])

We got the squared array and now let’s use the map function and add the array elements

function squareSum(numbers){
  const squared = numbers.map((number)=> Math.pow(number, 2))
    const sumSquared = squared.reduce((previous, current)=> previous + current, 0)

return sumSquared; //11
}
squareSum([1,2,3])

Here the 0 in the reduce function is the initial value. In the beginning, the previous value is 0(initial value), the current value will be 1 and adds 0 to 1 = 1

Next, the previous value becomes 1, the current value becomes 2 and adds 1 and 2 = 3, and so on until all the array elements are reduced to a single value.

We can minimize the above code to one line as follows

function squareSum(numbers) {
  return numbers.map((item) => Math.pow(item, 2)).reduce((prev, curr) => prev + curr, 0);
}
squareSum([1,2,3]) 11

Final Words

If you enjoyed this challenge, subscribe to my newsletter above and you will receive code war solutions right in your inbox.

Follow me on Github to see the solutions to these challenges before I break down here on HashNode.

You can check my other code wars solutions here:

  1. Calculate Average

  2. Cockroach Speed

  3. Sum The Strings