Sitemap
Tim Nelson

Tim Nelson

JavaScript Algorithms: Symmetric Difference

2 min readNov 21, 2018

I decided to start a series where I tackle basic algorithms head on. I’m getting my prompts from freeCodeCamp’s interview prep section. Each post will detail how I approached solving the code prompt.

Where to start:

The first step in creating an algorithm might seem pretty obvious but really it’s not: You must understand what problem you’re trying to solve. Case in point: when I first started working on Symmetric Difference, I thought I understood it so I launched into writing code right away. I thought all it meant was “find the elements that are unique to each array”. Unfortunately this was fundamentally incorrect.

So what is Symmetric Difference?

Well, to answer this I need to first explain where I went wrong. I read the first sentence of the instructions at freeCodeCamp:

Create a function that takes two or more arrays and returns an array of the symmetric difference (△or ⊕) of the provided arrays.

I thought I understood what it was. Given two or more arrays, return an array containing only unique elements — elements only found in one of the arrays. When providing only two arrays, this is correct. However, when providing more than two arrays, the rules change dramatically. To be honest, I found the instructions to be a little misleading because it seems to assume I already understood symmetric difference. Unfortunately, it had been a long time since I had taken an algebra class and I didn’t really remember Sets let alone Symmetric Difference. Here’s the missing information in the form of a very simple video with cool visuals:

Putting it all together

Get Tim Nelson’s stories in your inbox

Join Medium for free to get updates from this writer.

So to break it down, here are the procedures that must happen:

  1. Validate the parameters (they all must be arrays).
  2. Remove any duplicate items from each parameter.
  3. If only one parameter is provided, return that parameter (with duplicates removed).
  4. If more than one parameter is provided seed the unique variable using the first parameter then iterate over the remaining parameters comparing them against unique and replacing unique with the result.
  5. Return unique sorted from smallest to largest.

Tools we can use

ES6 gives us Set. A Set is a collection in which every item is unique. If you try to add an item that’s already in the Set, it has no effect. People coming from other languages (and mathematics) are very familiar with Setso it’s nice to finally have this tool in JavaScript.

And here’s the solution…

--

--