.reduce()

Hi coleagues!

I got extra exercise in this lesson
“Use .reduce() to take a multi-layered array and return a single layer array from scratch.”

It was difficult a bit so I found two decisions on the internet.

The first one

const array1 = [
  [1, 1, 1, 1], 
  [2, 2, 2, 2],
  [3, 3, 3, 3]
];

const reduced = array1.reduce( (acc, curVa) => acc.concat(curVa) );
console.log(reduced) ;

As I guess iterations for the first one looks like this:

  1. [1, 1, 1, 1] is acc;
  2. [2, 2, 2, 2] is curVa;
  3. join acc with curVa;
  4. acc becomes [1, 1, 1, 1, 2, 2, 2, 2];
  5. curVa becomes [3, 3, 3, 3];
  6. join acc with curVa again;
  7. [1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3] - our return.

Am I right?

The second one

const array1 = [
  [1, 1, 1, 1], 
  [2, 2, 2, 2],
  [3, 3, 3, 3]
];

const reduced2 = array1.reduce((acc, curVa) => {
  let newArr = [...acc, ...curVa];
  return newArr;
} );
console.log(reduced2);

I guess “…Name” takes every element of array until the last one.
What is the algoritm in this case?

It looks very odd.
Would you explain me how it works?

Reduce is just a for loop with a variable, just like how map is a for-loop that replaces each value, and filter is a for-loop that only keeps some values.
Try implementing reduce yourself, it doesn’t do very much and is therefore trivial to write.
The point of such functions is that you don’t have to write identical loops over and over and over and instead leaves you to focus on combining different parts of your code.

In this particular case you might not want to re-construct the whole array at each step and instead mutate a single array, appending each element to it. As an example, if there are a million elements, then you’d want to do about 1 million steps, not 500000million steps as a result of redoing previous work many times.

Regarding what happens as it runs, there’s nothing stopping you from using console.log to write thing out as they happen.

Also, note that concatenating array1 results in the final desired result.

> array1 = [ [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3] ]
> concat array1
[1,1,1,1,2,2,2,2,3,3,3,3]

So this task might not be the best example ever of reduce, because if it isn’t really helping, then what is it doing?