We will learn to use the filter()
method to create a function that takes two arrays representing two sets of elements and returns an array of all unique elements in the two submitted arrays. This is what we call the union, as introduced at the start of this shot.
Our input is made of two arrays of integers:
arr1 = [2, 4, 6, 8, 10]
arr2 = [1, 2, 3, 4, 5]
The expected output is:
arr3 = arr1 U arr2 = [1, 2, 3, 4, 5, 6, 8, 10]
. We know something about the union in mathematics. Now is the time to practice by implementing it in JavaScript. Considering the above examples, let's create two arrays of color strings that we will be using as a test example:
const arr1 = [2, 4, 6, 8, 10]const arr2 = [1, 2, 3, 4, 5]
Now, let's create the base function for our program:
function unionArr(arr1, arr2) {const arr3 = []return arr3}
We'll mainly use the filter()
method. In addition to it, we'll also use concat()
and includes()
:
filter()
: This creates a new array with all elements that pass a given test.concat()
: This merges arrays.includes()
: This checks if an array contains a given value/element.The syntax for filter()
looks like this: filter(callbackFn)
where callbackFn
is a function to test each element of the array. Let's implement this function.
First, let's define what we want to implement. Our goal here is to have a new array of arr2
elements that don't exist in arr1
. Concretely, if we consider our example, the function should return [1, 3, 5]
. Let's move to the code:
// input arraysconst arr1 = [2, 4, 6, 8, 10]const arr2 = [1, 2, 3, 4, 5]function isNotInArr1(elt) {return !arr1.includes(elt)}// output arrayconsole.log(arr2.filter(isNotInArr1))
As we can see, the function is just running as expected.
includes()
.filter()
with the callback function.Now, we concatenate this new array with arr1
.
//previous code hereconst arrFiltered = arr2.filter(isNotInArr1)const unionArr = arr1.concat(arrFiltered)
filter()
is stored in arrFiltered
.concat()
is stored in unionArr
.Let's put everything together and see how things look:.
// input arraysconst arr1 = [2, 4, 6, 8, 10]const arr2 = [1, 2, 3, 4, 5]// callback functionfunction isNotInArr1(elt) {return !arr1.includes(elt)}function unionArr(arr1, arr2) {const arrFiltered = arr2.filter(isNotInArr1)const unionArr = arr1.concat(arrFiltered)// sort the resultreturn unionArr.sort((a,b) => a - b)}// output arrayconsole.log(unionArr(arr1, arr2))
Line 15: We return the array already sorted using sort()
.