Question about reduce method - freeCodeCamp Algorithm Challenge Guide: Wherefore Art Thou

Hi, I have completed this challenge and now, I’m studying the example code.
I have trouble understanding the code in Advanced Code Solution.
I have read the “Code Explanation,” but I don’t understand the reduce method part.
I read about reduce and I understand what reduce method can do, but I just can’t understand why this reduce method work in this way.

  .reduce(function(a, b) {
    return a && b;
  });

Can anyone explain what this code above is doing?
Thank you.

freeCodeCamp Algorithm Challenge Guide: Wherefore Art Thou

5 Likes

The reduce() method is used on an array produced by the following:

srcKeys.map(function(key) {
  return obj.hasOwnProperty(key) && obj[key] === source[key];
});

Which is an array of either true or false, depending on whether or not all key-value pairs are present in a reference object (obj) in the collection. For example:

  • If obj is { a: 1, b: 2, c: 3 } and source is { a: 1 }, then the array produced is [true]
  • If obj is { a: 1, b: 2, c: 3 } and source is { a: 1, c: 3 }, then the array produced is [true, true]
  • If obj is { a: 1, b: 2, c: 3} and source is { a: 1, b: 2, c: 4 }, then the array produced is [true, true, false]

When the reduce method isn’t provided an initial value for the accumulator, the accumulator automatically takes the value of the first element in the array. As such, the code:

  myArray.reduce(function(a, b) {
    return a && b;
  });

effectively returns the logical AND (&&) of all elements in the array when the array has more than one element; that is, it returns true when all elements are true, and returns false otherwise.

When the array has only one element, the first value in the array is returned; here is the relevant bit in the documentation for reduce():

If the array has only one element (regardless of position) and no initialValue is provided, or if initialValue is provided but the array is empty, the solo value will be returned without calling callback.

I hope that helps. :slight_smile:

16 Likes

Hi honmanyau,

Thank you so very much for answering my question.
Your explanation answered my question and yes, it really helps me a lot.

Since I’m ESL, I have trouble understanding those explanation about method, but you explained it very well, so I was able to understand what this entire code was doing.

Thanks again!

1 Like

Tondemo arimasen, Myojin-san! Your English is perfectly fine—documentation can sometimes be oddly confusing even to native speakers! I’m glad that the explanation help! Good luck! :smile:

1 Like

Hi honmanyau,

Thank you for your encouraging word and trying some Japanese! :+1:
I’m gonna keep working hard so that I can write a beautiful code!

Thanks again! :slight_smile:

1 Like

I so needed this explanation… thanks to you both :slight_smile:

2 Likes

This was exactly what i needed. Thanks for asking the question so clearly and the great response!!!

1 Like