Here’s my code (not yet completed). I understand the reason my filter is not working (the === -1) doesn’t make sense since it’s not checking for “duplicates”, more so, just the existing of that item in the existing array, which will obviously not be -1 since it would just find itself. I’m confused how the solution doesn’t have this issue though, since it seems like its following the same logic with the filter, I believe.
My code:
function uniteUnique(arr) {
let newArr = Array.from(arguments)
let singleArr = newArr.reduce(function(a,b){
return a.concat(b);
})
let ans = singleArr.filter(function(a){
singleArr.indexOf(a) === -1
console.log(singleArr.indexOf(a) + ' a:' + a)
})
console.log(ans);
}
uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1]);
Solution
function uniteUnique(arr1, arr2, arr3) {
var newArr;
//Convert the arguments object into an array
var args = Array.prototype.slice.call(arguments);
//Use reduce function to flatten the array
newArr = args.reduce(function(arrA,arrB){
//Apply filter to remove the duplicate elements in the array
return arrA.concat(arrB.filter(function(i){
return arrA.indexOf(i) === -1;
}));
});
return newArr;
}
// test here
uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1]);