I can write out the logic or the pseudo code for how I approached this but I don’t want to rob you of the learning experience either.
I will also say that at first it seems like you would want to check the longer array against the shorter array because there will always be extra elements in the larger array that you want to check for and not skip but the shorter array might have a unique element so that logic would only work if we knew the shorter array did not contain any unique elements from the longer array.
Just wanted to mention that because in the code from your first post I see you sorting them and then getting the length and then looping through the longer array to compare against the shorter. I see how you are thinking about it.
Let me lay out my logic below now:
Take the first element of the first array and check it against each element in the second array until we find a match or reach the end of the second array.
If the element we are checking from the first array is found in the second array then we will stop going through the second array and move on to the next element from the first array, repeating the same process.
If the element from the first array is not found in the second array, because we’ve reached the end of the second array, then we can push the element from the first array into a new array that holds only the elements not found in the second.
Now repeat the same process but flip the arrays around starting with the first element from the second array and iterating through each element of the first array to find the elements only present in the second array and store them in a new array.
Now we have two new arrays, one which has the unique elements from arr1 and another withe the unique elements from arr2.
The last step is simple to concatenate these two arrays and return the result.
Let me know if this is helpful or not.
How may I compare every element of an array with every element of another array?
To answer your original question, this can be accomplished with a nested for loop or with the built in methods suggested in the help. Those being filter and includes.
Here is a simple nested for loop that will check all the elements of one array against another.
const arr1 = [1, 2, 3];
const arr2 = [4, 2, 1];
const arr1_Unique = [];
for (let i = 0; i < arr1.length; i++) {
for (let j = 0; j < arr2.length; j++) {
if (arr1[i] === arr2[j]) {
// If we find a match we can break
// out of loop and check next element
break;
} else if (j === arr2.length - 1) {
// If no match is found and we are at the
// end of the array, push element to unique array
arr1_Unique.push(arr1[i]);
}
}
}
The methods filter and includes could replace this and I’m sure many other solutions could work.
Make sure you are returning the final result instead of just console logging it.
Also, even though what you wrote still works, you should instead write !arr2.includes(element) with no space between the exclamation point and the statement.