Reducer function in reduce method

Hi everyone,

I am trying to understand the solution for exercise Find the Symmetric Difference and can’t figure out how the reduce method works in the below code. Could someone please help me understand step by step what is happening?

I understand the code until the reduce method is applied but I have no idea how the reduce method executes the symDiff function even though I think I have a basic understanding of reduce method. How does it know which element to assign to arrayOne and arrayTwo, where is the accumulator here? Basically I understand nothing.

``````  var args = [];
for (var i = 0; i < arguments.length; i++) {
args.push(arguments[i]);
}

function symDiff(arrayOne, arrayTwo) {
var result = [];

arrayOne.forEach(function(item) {
if (arrayTwo.indexOf(item) < 0 && result.indexOf(item) < 0) {
result.push(item);
}
});

arrayTwo.forEach(function(item) {
if (arrayOne.indexOf(item) < 0 && result.indexOf(item) < 0) {
result.push(item);
}
});

return result;
}

// Apply reduce method to args array, using the symDiff function
return args.reduce(symDiff);
}
type or paste code here
``````

Thank you so much!

symDiff is the callback function provided to `.reduce`. You’re probably used to seeing something like this:

``````const sum = array.reduce((acc, item) => acc += item)
``````

Here, you use an anonymous callback function and pass it directly into `.reduce`. In your code example, that callback function is “externalised” by defining it outside of `.reduce`, and then passing it in by the function name:

``````function addItems(acc, item){
acc += item;
return acc
}

const sum = array.reduce(addItems)
``````

Now as for the accumulator in your example:
The function starts with the first two arrays and compares them, and returns a combined array of unique items. In each iteration, whatever is returned (the `result` array) is the accumulator `arrayOne`, and `arrayTwo` is the next array that’s tested against the current accumulator.

I’m not sure if I have explained that well so ask again if it’s not clear.

1 Like

Oh now I understand how it works and why it works. Thank you so much for your help!

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.