Member-only story
JavaScript Algorithm: Array.diff
Implementing a difference function that subtracts one list from another
We are going to write a function called arrayDiff
that will accept two arrays, a
and b
, as arguments.
You are given two arrays. The goal of the function is to remove all values in array a
that is present in array b
. The function should return the array after all the common values have been removed.
Here are some examples:
arrayDiff([], [4,5]) //output: []
arrayDiff([3,4], [3]) // output: [4]
arrayDiff([1,8,2], []) // output: [1, 8, 2]
In the first example, there are no values in a
that are in b
. The array is empty by default so the function will return an empty array.
In the second example, only 3
from a
is found in b
so that number is removed and the function returns [4]
.
In the last example, all values in a
are not found in b
so the function returns [1,8,2]
.
To begin, we will create a variable called arr1
that will contain all the values that are present in a
but not in b
. This is the array the function will return. We assign it an empty array.
let arr1 = [];
If you look at the first and third examples above, we notice that if b
is empty, the function will return the a
array as-is. This also happens when the a
array is empty.
Because of that, we will write an if statement that checks if the array length of either a
or b
is zero. If it is, return a
as-is.
if(b.length === 0 || a.length === 0){
return a;
}
Along with the if-statement, we will also add in an else
statement. Inside the else block we will iterate through the a
array using the filter()
method and filter out all values that exist b
.
We assign the resulting array to arr1
and return it.
arr1 = a.filter(num => !(b.includes(num)));
Here is the full if-statement:
if(b.length === 0 || a.length === 0){
return a;
}else{
arr1 = a.filter(num => !(b.includes(num)));
return arr1;
}