Jon Newton

March 4, 2021

Array reduce, the interesting bits

Here’s the original snippet from the updateAverageRating function which uses Array.reduce to count all the review ratings.

  const total = location.reviews.reduce( (accumulator, rating) => { 
    return accumulator + rating;
  });

My code had two problems which left me puzzled in the debugger for a bit.

  • Why was rating a MongoDb document instead of the rating from that document?
  • Why was accumulator also a MongoDb document instead of a numeric counter?

When writing the callback function, I failed to notice the use of the destructuring curly brace syntax:

  { rating } 

This is a lovely piece of JS syntax which allows you to unpack values from objects in a really useful way. In this example, we are selecting the rating property of the document for use in the reduce arrow function.

The issue with the accumulator was due to a missing optional parameter to the reduce function: initialValue.

location.reviews.reduce( <callback>, 0);

About Jon Newton

Pandemic programming and beyond! My Link Tree