Hi people,
Just thought I’d post my code for the Diff Two Arrays
challenge, it takes advantage of Sets so the nice has()
method can be used. However how can I improve this? I feel like 2 for loops doing roughly the same thing is slightly inefficient.
/* jshint esversion: 6 */
function diffArray(arr1, arr2) {
const filteredSet = new Set();
const set1 = new Set(arr1);
const set2 = new Set(arr2);
for(let item of set1) {
if(set2.has(item)) {
continue;
} else {
filteredSet.add(item);
}
}
for(let item of set2) {
if(set1.has(item)) {
continue;
} else {
filteredSet.add(item);
}
}
const newArray = Array.from(filteredSet);
return newArray;
}
diffArray([1, 2, 3, 5, 7, "test string"], [1, 2, 3, 4, 5]);
Some guidance on how to improve this would be great!
Thanks!
James.