2

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()]

jpls93
  • 614
  • 1
  • 7
  • 19

1 Answers1

2

You could use a Set for this.

function removeExtra() {
    const uniques = new Set();

    for(const array of ...arguments) {
        for(const element of array) {
            uniques.add(element);
        }
    }

    return Array.from(uniques);
}
Coloured Panda
  • 3,293
  • 3
  • 20
  • 30
  • Wow, thanks for the Big O Notations. What reference would you recommend for studying more about it? – jpls93 Aug 01 '16 at 10:07
  • @JohnPatrick Here's a ES6 reference to the Set structure http://www.ecma-international.org/ecma-262/6.0/#sec-set.prototype.add It is implemented in a hashmap so its not lineral, but its also not in logarithmic time. Performance is faster, as Array.indexOf cannot benefit from this – Coloured Panda Aug 01 '16 at 10:39