Get the Difference Between Two Arrays in JavaScript

Create and Array from the difference between two arrays in JavaScript

Sometimes we want to compare the difference between two arrays in JavaScript and return the remaining values in a new array.

This can be useful for inventory or purchase management where we could compare the selected items against the available stock, for example.

In this tutorial, we will cover two approaches to this:

  1. A single set of unique items in an array.
  2. A main array containing duplicate items.

Let’s get cracking!

The Video Tutorial

Get the Difference Between Two Arrays in JavaScript containing only unique items

In this section, we will cover two common approaches to returning a new array containing the remaining items of a set array.

What do I mean by ‘set’? A set contains only unique items in an array.

Let’s say we have two number arrays. We want to check if any values in array2 appear in array1.  If so, then we don’t want to include them in our new array.

Our new array should look like this:

 newArray = [1, 3, 5];

Hire a Google Workspace Developer for your Business Needs

First solution

This array takes a main_array (In our example this would be array1) and an array containing items to delete from the main array (In our example this would be array2), the del_array.

We then call a JavaScript filter method on the main array allowing us to filter down to only the items that we want returned in our new array.

The filter method takes a callback function as an argument. This method will return any item based ‘truthy’ condition.

Here we have generated an inline arrow function for this purpose, where item is our iterator represents the value of each item in the array.

What items do we want to be returned in our new array? We want anything that is not included in our del_array erhm…array.

‘Includes’ is the keyword here. JavaScript has the includes() method that allows us to check if a selected item is included within the target array. If the item is found then the method will return true otherwise it will return false.

Here we add our item iterator as the search argument.

Finally, we want to return anything that is not found from the ‘includes’ method. We do this by prefixing the method call with the bang (!exclamation mark) ‘not’ logical operator.

This function could also be used inline and can also be used with strings.

Console this rather Baludur’s Gate 3 thirsty example:

Second Solution

We can solve the same problem by replacing the includes method with the JavaScript indexOf method. This method iterates through an array and returns the position index of the argument item. If the returned position is -1, then the item does not exist in the array.

🐐You can support me for free by using this Amazon affiliate link in your next tech purchase :Computers & Stuff! 🐐

In our example above, we return any item that does not exist in the array.

Go ahead and give this second solution a try.

One overlooked problem

A commonly overlooked problem with this solution occurs when there are duplicate items in the main array.

Give this a try:

You will have found that the result was:

[1, 3, 5]

Rather than the anticipated:

[1, 2, 2, 3, 5, 6, 6, 6]

The function removes all instances of the found values.

How do we fix this?

Get the Difference Between Two Arrays where the main array contains duplicates

Whenever we find an item from our delete array in our main array we should remove it from the arrays to search for on each iteration over the main array otherwise we will experience the problem above.

Let’s look at another two solutions to this.

Solution 1 – Rebuilding the delete array

In this example, we will create a separate copy of the del_array called the subrahend using the spread syntax (Line 2). This way we won’t directly edit the del_array when we take an item from it.

Then we will carry out our ‘filter’ method again using indexOf to find if there is an index. This time around we store the result in the delIdx variable because we will use it two more times.

Next, we check if the delIdx doesn’t exist, if this is the case, we return the item to the new array. Otherwise, we use the JavaScript splice method to delete the found value from the subtrahend array so it can be indexed on the following iterations of the ‘filter’ method.

Splice takes two arguments, the start index and the number of items to remove.

Give it a try:

Your result now should be:

Solution 2 Using the second argument of indexOf

In this example, instead of rebuilding the delete array each time, we make use of the ‘indexOf’ method’s section optional parameter fromIndex. This parameter allows us to add a starting position to commence our indexing search.

Create and Publish Google Workspace Add-ons with Apps Script Course 300px

This means that if we do get a match in our delete array, we could add one to the index that it is found at and commence the next search in the del_array from that position.

One line 2 we now add a start position beginning at zero.

Then we include that variable as the second argument of the ‘indexOf’ method.

In our else-statement this time, when an item is found, we get the item index in the delIdx and add one before updating the indexOf_start variable for the next iteration through the main array.

The Reference Code

This section contains the 4 full functions with JSdoc comments for easy reference along with some test logs.

References used:

For the Google Apps Script Developer

This is a particularly handy set of functions that you can use to compare two ranges in a spreadsheet and return a separate array. You could use the JavaScript flat method here to flatten the 2d array before comparison.

 

~Yagi

Leave a Reply