How does the accumulator value in reduce method change without explicitly changing it?

Viewed 1023

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]
1 Answers

You will probably understand it better seeing this rudimentary version of reduce that simply sums the array values when called

Array.prototype.myReduce = function(callback, start) {
  // inital value of acc is start value `0` set in call
  let acc = start; 

  this.forEach((elem, i) => {
    // acc gets assigned the return value from the callback 
    // every iteration of this internal loop
    acc = callback(acc, elem, i, this)
  });
  // then finally gets returned from the outer function
  return acc
};

const arr = [1, 2, 3]

const res = arr.myReduce((a, c, i, arr) => {
  return a + c // returned to `acc` in the forEach loop above
}, 0)

console.log('Result:', res) // expect 1+2+3 = 6

Related