Trying to practice my (now rusty) algo writing skills so this code is gonna look a little rough but I’d like to power through and re-build algo skills and knowledge rather than just read answers.
My pseudo-code for this is:
- Create unique arrays out of each of the args sent in.
- For each of those unique arrays compare to every other array to see if this array has any number that don’t exist in any of the others. If so, push it to an empty
result
array.
Where I’m having trouble is getting to the last array. I know it’s b/c I am limiting the for
loop till k < interArray.length - 1
but of course if I don’t do that, then it will look for k[interArray.length]
which doesn’t exist.
Code so far:
function sym(...args) {
let interArray = [];
for (let i = 0; i < args.length; i++) {
const uniqueSet = new Set(args[i]);
const backToArray = [...uniqueSet];
interArray.push(backToArray);
}
let result = [];
for (let k = 0; k < interArray.length - 1; k++) {
for (let i = 0; i < interArray[k].length; i++) {
if (interArray[k + 1].indexOf(interArray[k][i]) === -1) {
result.push(interArray[k][i]);
}
}
}
console.log(result);
return result;
}
sym([1, 2, 3, 3], [5, 2, 1, 4], [5, 2, 21, 34, 2, 1]);
Challenge: Find the Symmetric Difference
Link to the challenge: