Sorted Union Code Problem (reduce method)

Hi,

I am having some difficulty with the Sorted Union problem.

Here is my current code. I guess I am not really grasping how the reduce() method syntax operates. I read through the MDN doc and I don’t understand a few things.


function uniteUnique(arr) {  
  var a = arguments;
  var b =[];
  //convert arguments into an array of arrays
  for(i = 0; i<a.length; i++){
     b[i] = a[i];    
    }
  //flattens array one tier (leaves 3rd nested values)
  var f = b.reduce(function(c,b){
    return c.concat(b);
  });
  //Removes repeat values.
  var g = f.reduce(function(all, item){
    if(all.indexOf(item) == -1){
      return all.concat(item);
    }
   }
  );
  return g;

 }
uniteUnique([1, 3, 1,2], [5, 2, [1], 4], [2, 1]);

Why do some people put a “[]” after the closing curly braces? Why would I need to use a forEach function within the reduce? I guess I don’t know why nesting an indexOf() within a reduce within an if does not work. I get a “all.indexOf()… is not a function”.

Please help.

Thanks.

I ended up using filter instead.


function uniteUnique(arr) {  
  var a = arguments;
  var b =[];
  //convert arguments into an array of arrays
  for(i = 0; i<a.length; i++){
     b[i] = a[i];    
    }
  //flattens array one tier (leaves 3rd nested values)
  var f = b.reduce(function(c,b){
    return c.concat(b);
  });
  //Removes repeat values.
  var unique =  f.filter(function(x,i){
      return f.indexOf(x)===i;
  });
  return unique;

}
                   
uniteUnique([1, 3, 1,2], [5, 2, [1], 4], [2, 1]);

I am practicing functional programming,
so I’ve built this one-liner with reduce:

// spreading (…arr) the input param
// reduce to concat the arrays
// create a new Set to remove duplicates
// spreading ([…new Set()]) the Set back into an array

const uniteUnique = (…arr) => […new Set(arr.reduce((a, b) => a.concat(b)))];