This series answers coding interview questions from the Coding Interview Prep collection at freeCodeCamp. You can find more with the interview questions tag.
The concept is to find the numbers in two arrays that do not repeat in both. So [1,2]
and [2,3]
would produce [1,3]
. If you’re comparing more than 2 arrays, you compare the next array (and beyond) to the result of the last comparison. So [1,2]
, [2, 3]
, and [2,4]
would produce [1,2,3,4]
because 2 is filtered out of the first comparison and it isn’t in the result being compared in the next, so it comes back.
Solution explained
First, the args
argument (provided in the scaffolded function) only gives you the first array submitted as an argument. It should just be ignored. Use the arguments
object instead to get an array of all the arguments.
- Create an array(
result
) to hold the results. -
Run through the
arguments
array with a loop (i
). Start by filtering duplicates from the array using the spread operator andSet
function. -
With another loop (
j
), check each number in the filtered set to see if it appears inresult
. If it’s not there, add it withpush
. If it’s already there, remove it withslice
. -
The result of the first pass of the loop will add the first array to the loop in its entirety. The result of each successive pass will perform a symmetric compare between the next array (
arguments[i]
) with theresult
array. -
Finally, do a sort on
result
(requiring the function we pass toresult.sort()
as an argument to ensure a numeric sort instead of alphabetic) because the tests require the result to be sorted to pass.
Solution
function sym(args) { let result = []; for(let i in arguments){ let filtered = [... new Set(arguments[i])]; for(let j in filtered){ let number = filtered[j]; if(result.indexOf(number) === -1){ result.push(number); } else { result.splice(result.indexOf(number), 1); } } } result.sort(function(a, b) { return a - b; }); return result; }