I am trying to recreate the underscore js function difference using reduce. Difference takes in multiple arrays and returns all values that are similiar to the first array. so [1,2],[2,3],[1,3] should spit out [1,2,2,1].
I was thinking of looping through each of my subarray(rest) and if the value of my sub elements has an index in my first array then I will push that element onto my accumulator value(which is an empty array).
Some reason I do not get my intended output where I was expecting [1,2,3,2,1,2]. instead I am getting [ [ 1, 2 ], [ 2, 4 ], [ 1, 2 ] ]. Can anyone help me with this rewrite using reduce. Thanks.
function difference(arrays){
var arrayed=Array.prototype.slice.call(arguments);
var first=arrayed[0];
var rest=arrayed.slice(1);
return reduce(first,function(acc,cur){
forEach(rest,function(sub){
if (sub.indexOf(cur)>-1){
acc.push(sub);
}});
return acc;
},[]);
}
console.log(difference([1,2,3],[2,4],[1,2],[4,5]));
i know the way im calling forEach is different but it is because my own version of forEach accepts two arguments.