Sorted Union Code Problem (reduce method)

Sorted Union Code Problem (reduce method)
0.0 0

#1

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.


#2

In the first iteration of the following reduce:

  var g = f.reduce(function(all, item){

all = 1 and item = 3, so since all is a number and not an array, all.indexOf results in the error, because there is no indexOf function for numbers.

FYI - Before the above reduce line, f is an array which looks like:

[ 1, 3, 1, 2, 5, 2, [ 1 ], 4, 2, 1 ]


#3

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