Search code examples
javascriptarraysobjectreducerscomputed-properties

JavaScript computed properties


I am following James Moore's Functional programming for beginners with JavaScript course. However, I am currently having difficulties understanding the following code:

const reviews = [4.5, 4.0, 5.0, 2.0, 1.0, 5.0, 3.0, 4.0, 1.0, 5.0, 4.5, 3.0, 2.5, 2.0];

const countGroupedByReview = reviews.reduce(groupBy, {});

function groupBy (acc, review){
  const count = acc[review] || 0;
  return {...acc, [review]: count + 1}
}

While I understand the way in which the reduce method works, I am struggling to make sense of the code within the groupBy function block. I believe this has something to do with computed property names. I would be very grateful for any help.

Thanks.


Solution

  • It don't think there's any computed property names in the code block. What this block of code does is that it counts the number of occurrence of each review score in the array. Let's step through the callback with its arguments first:

    The callback accepts 2 arguments:

    • acc is the accumulator, which is the data that the reducer will keep pushing into. It is first defined as a blank object, as the second argument in Array.prototype.reduce
    • review is simply the current item in the array that is currently being iterated through

    Now into the code of the callback itself. The line const count = acc[review] || 0 simply means:

    1. If the array item exists as a key in the accumulator, then return its value
    2. If the array item does not exist as a key in the accumulator, then set its value to 0

    After that, you simply increment the count by 1, because you have just encountered the item and you want to add it to the total tally, grouped by the array item's value. The { ...acc, [review]: count + 1 } is simply an object spread function, that simply means: retain whatever key-value pair I have for the accumulator, but merge in changes done for a particular key-value pair.