This is my first time writing here, so apologies in advance.
I am pretty sure I have a good grasp on the reduce() method, but I can't seem to wrap my head around one concept in particular. In this particular problem, we are asked to find elements that all of the array arguments share. I was able to construct an answer with the reduce method. I know that it works, and I know there are more efficient solutions, but I can't seem to understand how the accumulator value revises itself even though I have not reassigned its value.
Let me explain: after the first iteration of the current values which is the second array, I check to see if the current elements share commonalities with my accumulator(the first array). After checking and pushing the common values into results, results = [5, 15, 7]. The accumulator value at the beginning of the next iteration also becomes my set of results values, but again, I do not explicitly reassign the accumulator value, for example with acc = results . How does accumulator "understand" to change without explicit changes? I've kinda just accepted this mechanism as is, but would love an explanation. Please let me know if I should offer more clarification. Thank you!
function intersection(arrays) {
return arrays.reduce((acc, curr) => {
// here, acc = the first array --> 5, 15, 7 --> 15, 5
let results = []
for(let element of curr) {
if(acc.includes(element)) results.push(element)
}
// here, results = 5, 15, 7 --> 15, 5 --> 15, 5
return results
})
}
const arr1 = [5, 10, 15, 20, 7, 3];
const arr2 = [15, 88, 1, 5, 7, 21];
const arr3 = [1, 10, 15, 5, 20, 21];
console.log(intersection([arr1, arr2, arr3]));
// should log: [5, 15]