Two Simple Ways to Sum an Array in JavaScript
Code challenges are a common way to reinforce your understanding of the concepts related to a certain language. In addition to brushing up your skills on the basics, it’s also a way for potential employers to see your efficiency as a problem solver. As with any problem, there are multiple ways to solve the same question.
Let’s take a look at HackerRank’s challenge Simple Array Sum. We’ll be solving this two ways using JavaScript: using a simple for loop and Array.prototype.reduce().
Now, we’ll break this problem down before we start trying to solve it!
HackerRank gives us the sample input where 6 is the length of the array, or the number of elements inside that particular array. In the next line, they show the numbers represented inside that array. Notice that there are exactly 6 numbers associated with that particular array.
The problem states that it expects us to return the number 31 as the sum of that array. We can go about solving this problem in two different ways: a for loop or the .reduce() method.
For Loop
First, we’ll solve this with a for loop. Consider this as your empty base function:
function sumSimpleArray(array) {}
We have a function called sumSimpleArray that takes in an array as an argument.
Inside the function, we will need to set a variable to hold our sum:
function sumSimpleArray(array) {
let sum = 0;
}
We initialize the variable with the keyword let since we’ll be changing its value.
Next, we need write our for loop which consists of 3 parts or expressions. It takes in an initializer (or Initial Expression), test condition (or simply the condition), and final expression(or Increment Expression). These are typically written in one line called an iteration statement and separated by semicolons. This makes the for loop much more readable.
The initialization, you may have guessed, initializes or starts the loop. It is executed only once at the start of the loop. This is typically set to i=0 or more verbosely, index equals 0. The test condition which returns a boolean value of true or false. If the condition is true, the body of the loop is executed, otherwise the loop terminates or stops. The final expression is invoked after each iteration and typically increments or decrements the loop counter.
Now that we understand the parts, let’s get to writing:
function sumSimpleArray(array) {
let sum = 0;
for(let i = 0; i < array.length; i++) {
sum += array[i];
}
return sum;
}
Our test condition for this function is set to the length of the array so our loop knows when it needs to stop. Our final expression increments the index starting at index 0 and stopping at the last index of the array.
Next, we write our mathematical expression or block statement inside the for loop. Here we are stating that the variable sum will equal the current sum plus the next number in the array. Then, we return the value of the new sum. Notice that I used the keyword return. In JavaScript, we must use the return keyword unless we’re writing an ES5+ function in one line.
Reduce Method
The .reduce method executes a reducer function (or callback function) that returns a single value after iterating through the elements of an array. We are responsible for writing the reducer function.
A reducer function takes 4 arguments: Accumulator, Current Value, Current Index, and Source Array. The last two arguments are optional and we will not be using them in this example.
First, let’s write our reducer!
function sumSimpleArray1(array) {
const reducer = (accumulator, currentValue) => {
return accumulator + currentValue
}
}
In our function reducer, the return value becomes the accumulator value for the next iteration. currentValue takes on the value of the current element in the looping process.
Next, we will write our reduce method and return the value:
function sumSimpleArray1(array) {
const reducer = (accumulator, currentValue) => {
return accumulator + currentValue
}
return array.reduce(reducer)
}
This will also return the same value as the for loop from before! We can also write the same function above like this:
function sumSimpleArray2(array) {
return array.reduce((accumulator, currentValue) => {
return accumulator + currentValue
})
}
Now you’re ready to sum arrays with two different methods! Personally, I prefer the reduce method as it looks much cleaner. However, it is important to know both processes as the for loop is one of the building blocks for looping.
Take your new knowledge and continue testing your understanding!