I have a straightforward solution for the problem:
function removeExtra(arr) {
var args = [...arguments]
.reduce(function(prev,curr){return prev.concat(curr)});
var answer = [];
for (var i = 0; i < args.length; i++) {
if (answer.indexOf(args[i]) == -1)
answer.push(args[i]);
}
return answer;
}
console.log(removeExtra([1, 3, 2], [5, 2, 1, 4], [2, 1]));
//-> Returns [1, 3, 2, 5, 4]
But, I'm trying to practice the logic of JavaScript's functional methods, in this case, .filter()
. Is there a way to do it this way?
function removeExtra(arr) {
return [...arguments]
.reduce( (pre,cur) => pre.concat(cur) )
//.filter( x => ??? );
}
console.log(removeExtra([1, 3, 2], [5, 2, 1, 4], [2, 1]));
//-> Should be [1, 3, 2, 5, 4]
Edit 1:
As suggested, currently looking into Set()
. This is the first time I encountered it. Be right back for research work!
Edit 2:
BIG thanks to @Kaspars and @gcampbell for introducing Set()
!!
I now have my solution:
function removeExtra(someArgs) {
return [... new Set(
[...arguments].reduce(function(prev,curr){
return prev.concat(curr);
})
)]
}
This is just a minor revision to gcampbell's answer since I have to convert the Set
back to an Array
using [... new Set()]