JavaScript: Sum All Numbers in a Range and Diff Two Arrays

CodeDraken
Dev Compendium
Published in
5 min readOct 25, 2019

--

A walkthrough for two intermediate algorithm challenges on freeCodeCamp.

Beginner Skill level
Medium doesn’t let you left-align an image so here’s a massive banner

Prerequisites

Just a basic knowledge of JavaScript.

challenge descriptions

Sum All Numbers in a Range

The challenge description:

We’ll pass you an array of two numbers. Return the sum of those two numbers plus the sum of all the numbers between them. The lowest number will not always come first.

For example, sumAll([4,1]) should return 10 because sum of all the numbers between 1 and 4 (both inclusive) is 10.

sumAll([1, 4]) should return 10
sumAll([10, 5]) should return 45

FreeCodeCamp

Step 1 Understand the Problem & Examples

First, restate the problem in your own words and understand it from a high level. Here, we just want the sum of numbers from N to X.

Our function should:

  • Take in an Array with two unsorted numbers
  • Create a range of numbers between the two numbers
  • Return the sum of all those numbers including the two passed in

Step 2 Begin Thinking about the Code

Next, we write out pseudo-code of the steps we will take.

pseudo sum all in range

Note: We still have written no code yet and you might be eager to jump into coding when trying to solve problems but it’s better not to. Take your time, plan what you will do before writing any code.

Step 3 Research and Solve

Fill in the blanks from the pseudo-code you’ve written. If you don’t know how to do something, then check the documentation, Google, or this means you need to simplify it more and break it down into several pieces.

Try to solve it now before continuing.

// Figure out the minimum and maximum numbers in the array

We know this deals with numbers and there are two main pages for working with numbers in JavaScript on the documentation — Numbers and Math.

If you scroll through those two pages, you’ll quickly find Math.min() and Math.max() functions that can take in any amount of numbers and return the minimum/maximum, respectively. If you check their individual pages for more information, you’ll find you can use it directly on an Array by using the spread operator which looks like this: Math.min(…array1)

Next up, we need to figure out how to add a range of numbers from X to Y. If you check the documentation again you won’t find any range or sum function, unfortunately. Since we know the minimum and maximum, we can just do this ourselves manually with a loop.

sumAll solution 1

Step 4 Review and Refactor

We are not done yet! Now is when you would refactor your solution to be neater, faster, and optimized. (or just mess around for fun) Here are a few more ways to solve this challenge.

Math Solution:
Often there are math solutions that are more concise, faster to write, and more performant than writing a bunch of code that does the same thing.

sumAll math solution

Break it Down:
Don’t be afraid to split your code up into many functions. Doing this lets you simplify your logic, reuse code more easily, and it results in clean, easy-to-understand solutions.

sumAll functional solution

Do Something Crazy:
Experiment and have fun with it. Because this challenge is simple, it’s a good candidate to play with new methods and techniques.

sumAll Experimental

Diff Two Arrays

Challenge description:

Compare two arrays and return a new array with any items only found in one of the two given arrays, but not both. In other words, return the symmetric difference of the two arrays.

Note: You can return the array with its elements in any order.
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/diff-two-arrays

Step 1 Understand the Problem & Examples

It gives us two Arrays and we want to create a new Array that includes elements that are not present in both.

Our Function Should:

  • Take two Arrays as input
  • Figure out which values exist only in one Array
  • Return a new Array of those unique elements
  • Edge Case: What if one Array includes an element twice i.e. [1, 2, 1], [3,2,4] the 1 values are only in the first Array but would we include it twice or just once in the returned Array? For now, we’ll just assume there are no Arrays with duplicates.

Step 2 Begin Thinking about the Code

Pseudo-code incoming:

diffArray pseudo-code

Step 3 Research and Solve

One thing you might notice immediately is that there are a lot of Arrays here which means we should check the documentation for any methods that might be useful.

Attempt the challenge if you haven’t already at this point.

The most relevant methods for this challenge would be: .includes .filter .concat .indexOf

// add unique values to newArr

Instead of adding unique values immediately we can make newArr a combination of arr1 and arr2 this way we only need one loop instead of two. To do this, we make use of the .concat method or the spread operator used in the previous challenge above.

const newArr = arr1.concat(arr2)
const newArr = [...arr1, ...arr2]

Now we have all values in newArr but we want to filter out values that are not in both Arrays. As you might’ve guessed, we’re using filter and .inlcudes here.

diffArray solution 1

The filter method keeps/removes values when you return true/false.

When an Array does not include a value, .includes(val) returns false but we invert it using the “logical NOT” operator, ! because we’re looking for values that do not exist in one Array.

For example, let’s say the value is 4 and arr1 does not include it but arr2 does. We would end up with something like this:

arr1 = [1, 2, 3, 5], arr2 = [1, 2, 3, 4, 5]!arr1.includes(4) -> !false -> true

After it reaches true, it stops and the filter function keeps it in the Array. Let’s look at it again but using val = 1 this time.

arr1 = [1, 2, 3, 5], arr2 = [1, 2, 3, 4, 5], newArr = [1, 2, 3, 5, 1, 2, 3, 4, 5]// keep this value if
!arr1.includes(1) -> !true -> false
// or
!arr2.includes(1) -> !true -> false
// both options were false we don't want this value
// *plop*
newArr = [2, 3, 5, 1, 2, 3, 4, 5]

Step 4 Review and Refactor

There’s not much we can do to improve our solution but I encourage you to try other techniques and experiment with it. I’ll leave this as a challenge for you. 😄

One line solution:

diffArray one liner

Thanks for Reading!

If you have questions or would like to share your solutions, then leave a comment below.

More Challenges

--

--