Solving "Diff Two Arrays" / freeCodeCamp Algorithm Challenges
Tags: freecodecamp, algorithms, challenge, javascript
Published: 2020-07-02 18:20:01

---
title: Solving "Diff Two Arrays" / freeCodeCamp Algorithm Challenges
published: true
description: My guide, notes, and solution to freeCodeCamp's basic algorithm challenge, "Diff Two Arrays" 
tags: #freeCodeCamp, #algorithms, #challenge, #javascript
canonical_url: https://virenb.cc/fcc-018-diff-two-arrays
series: Solving freeCodeCamp's Algorithm Challenges
---

!['Diff Two Arrays' ](//images.ctfassets.net/yzwpq1epaq68/7rvRyI3yu4l4cGGhBG4IAN/95254f522752a81497ea67f25d73202e/ss-018.png)

Let's solve freeCodeCamp's intermediate algorithm scripting challenge, 'Diff Two Arrays'.

### Starter Code
```javascript
function diffArray(arr1, arr2) {
  var newArr = [];
  return newArr;
}

diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]);
```

### Instructions

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.

### Tests

```
diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]) should return an array.
["diorite", "andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite", "andesite", "grass", "dirt", "dead shrub"] should return ["pink wool"].
["diorite", "andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite", "andesite", "grass", "dirt", "dead shrub"] should return an array with one item.
["andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite", "andesite", "grass", "dirt", "dead shrub"] should return ["diorite", "pink wool"].
["andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite", "andesite", "grass", "dirt", "dead shrub"] should return an array with two items.
["andesite", "grass", "dirt", "dead shrub"], ["andesite", "grass", "dirt", "dead shrub"] should return [].
["andesite", "grass", "dirt", "dead shrub"], ["andesite", "grass", "dirt", "dead shrub"] should return an empty array.
[1, 2, 3, 5], [1, 2, 3, 4, 5] should return [4].
[1, 2, 3, 5], [1, 2, 3, 4, 5] should return an array with one item.
[1, "calf", 3, "piglet"], [1, "calf", 3, 4] should return ["piglet", 4].
[1, "calf", 3, "piglet"], [1, "calf", 3, 4] should return an array with two items.
[], ["snuffleupagus", "cookie monster", "elmo"] should return ["snuffleupagus", "cookie monster", "elmo"].
[], ["snuffleupagus", "cookie monster", "elmo"] should return an array with three items.
[1, "calf", 3, "piglet"], [7, "filly"] should return [1, "calf", 3, "piglet", 7, "filly"].
[1, "calf", 3, "piglet"], [7, "filly"] should return an array with six items.
```

---

# Our Approach

**Read** everything first. **Read** the instructions clearly, **read** the starter code we're given, and **read** the tests and understand what has to be returned.

* The function takes in two arguments, `arr1` & `arr2`, both being arrays containing various data types (or being empty).
* We need to return an array with the 'symmetric difference' of the two arrays (items found in one of the two arrays but not both).

Now that we understand what we are given and what we want to output, let's see how we can solve this.

After reading and thinking about how to approach this problem, I would conclude looping through each array and comparing each item against the other array (to check if it exists) would be a good way to go about it.

Since we've been introduced to newer array methods in the fCC curriculum, it may be a good idea to see if any of them can be implemented in this solution.

Instead of (for) looping, another approach is possibly to combine the arrays and then see which item exists more than once. If there is such a case, we can then remove the item which is there multiple times.

Reading through documenation on my favorite website, [Mozilla Developer Network (MDN)](https://developer.mozilla.org/en-US/ "MDN"), we can see what array methods can help us out.  

#### [Array.concat()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat "MDN: concat()")

`Array.concat()` combines two or more arrays. It will return you a new array (instead of altering your existing ones).

```
diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5])

let newArr = arr1.concat(arr2);

newArr = [ 1, 2, 3, 4, 5, 1, 2, 3, 5 ]
```

We now have all our items from `arr1` and `arr2` combined into a new array. We now have to figure out if an item exists more than once and also how to remove it from the array.

The next useful new method we stumble upon is `filter()`.

#### [Array.filter()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter "MDN: filter()")

`filter()` will return a new array with all items which pass the constraint (or 'test implemented'). Small example as follows:

```
const nums = [1, 4, 9, 16, 25, 36, 49];

const doubleDigits = nums.filter(num => num > 9);

console.log(doubleDigits);
// Array(4) [ 16, 25, 36, 49 ]
```

We need to write a test within our `filter()` method to check if each item is from/in both arrays, `arr1` and `arr2`.

Another method which we will be using along with `filter()` is `includes()`. `includes()` checks if the value is in the array and returns a `true` or `false`.

So our `filter()` method will go through each item in our `newArr` and then check, using `includes()`, if the item is not in `arr1` or `arr2`. If it returns (true), that will mean the item is only in one of the arrays, which is what we want. So if it works correctly, each true value will be in an array.


#### [Array.includes()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes "MDN: includes()")

```
newArr.filter(item => !arr1.includes(item) || !arr2.includes(item))
// We're filtering the item if is NOT in arr1 OR it is NOT in arr2
```

So, to sum it up:

* Combine `arr1` and `arr2` into a new array, `newArr`, using `concat()`
* On `newArr`, run `filter()`
* In `filter()` method, check if each item is not in `arr1` OR not in `arr2` using `includes()`
* Return `newArr`

---

# Our Solution

> :warning: 
> :warning: **Answer Below**
> :warning: 

  
```javascript
function diffArray(arr1, arr2) {
  let newArr = arr1.concat(arr2);
  return newArr.filter(item => !arr1.includes(item) || !arr2.includes(item));
}
```


---


### Links & Resources

['Diff Two Arrays' Challenge on fCC](https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/diff-two-arrays "Intermediate Algorithm Scripting: Diff Two Arrays on fCC Website")

[freeCodeCamp](https://www.freecodecamp.org/, "freeCodeCamp")

[Donate to FCC!](https://www.freecodecamp.org/donate "fCC Donation Page")

[Solution on my GitHub](https://github.com/virenb/fcc-algorithms/blob/master/018---diff-two-arrays.js  "GitHub Solution")

Thank you for reading!