 # Refractor Diff. Two Arrays Code

I recently finished the diff. two arrays challenge in the intermediate scripting algorithms section of the JS certification and was wondering if my solution can be slimmed down a bit.

``````function check(cArr1, cArr2) {
// First, map a new array from arr1 containing values not found in arr2...
let filterArr1 = cArr1.map(
function(a) {
if (cArr2.includes(a) == false) {
return a;
}
}
// Then filter out any [""] values. These occur when the arrays are of different lengths.
).filter(a => a);
// Do the same thing in reverse...
let filterArr2 = cArr2.map(
function(a) {
if (cArr1.includes(a) == false) {
return a;
}
}
).filter(a => a);
return filterArr1.concat(filterArr2);
};

function diffArray(arr1, arr2) {
return check(arr1, arr2);
}

console.log(diffArray([1, "calf", 3, "piglet"], [7, "filly"]));
``````

What is the purpose of the following part?

``````let filterArr2 = cArr2.map(
function(a) {
if (cArr1.includes(a) == false) {
return a;
}
}
)
``````
1 Like

It iterates though the second array’s values to find elements not present in the first array and maps them to a new array.

If I comment out that code block, the function will not be able to pass the tests when both arrays contain unique elements.

For example, if I remove that code block and call diffArray([1, 2, 3], [4, 5]), the returned value will just be [1, 2, 3] when the resulting array should be [1, 2, 3, 4, 5]. So I have to keep it there for now.

You don’t need the map method. You can simply use the filter method.

``````let filterArr1 = cArr1.filter(a => cArr2.includes(a) == false);
``````

OR more concisely:

``````let filterArr1 = cArr1.filter(a => !cArr2.includes(a));
``````

The `diffArray` function is unnecessary, you could just do this

``````console.log(check([1, "calf", 3, "piglet"], [7, "filly"]));
``````
1 Like

The above function is not needed. Instead, remove it and rename your `check` function to `diffArray`.

1 Like