Symmetrical Difference_Receiving TypeError Message_Help Needed

Symmetrical Difference_Receiving TypeError Message_Help Needed
0.0 0

#1

Hello. I am unable to use the .forEach() method twice in my function. Could someone explain why this might be? Many thanks. They TypeError message I am receiving states “arr1.forEach is not a function.”

Code:

function sym(args) {
var argsArr = [].slice.call(arguments);

function symdif(arr1, arr2) {
  var values=[];

  arr1.forEach(function(num){
    if(arr2.indexOf(num) < 0 && values.indexOf(num) < 0){
      values.push(num);
    }
  });

  arr2.forEach(function(num){
    if(arr1.indexOf(num) < 0 && values.indexOf(num) < 0){
      values.push(num);
    }
  });
  return values;
}

return args.reduce(symdif);
}

sym([1, 2, 3], [5, 2, 1, 4]);


#2

The two parameters that reduce takes are 1) the previous item (sometimes called the accumulator, and 2) the current item in the array being reduced. Now, I can tell that you’re expecting arr1 to be [1,2,3] and arr2 to be [5,2,1,4], but arr1 is actually 0 and arr2 is [1,2,3]. This is because the accumulator is either specified by the second parameter passed to reduce, or 0 by default.


#3

The only problem I see with your solution is you assign argArr an array of the function arguments (which is correct), but then you call the reduce function on args instead of argsArr.