Advertisement
Guest User

Untitled

a guest
Mar 22nd, 2019
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.75 KB | None | 0 0
  1. # What exactly is the point of .reduce()?
  2.  
  3. Hey friends. I was really struggling with reduce() and knowing when to use it (and how to use it) and I don’t think I have been the only one. So if you are still struggling, read on! If not, tldr.
  4.  
  5. Something I really needed to know was this: what exactly is the point of reduce()? And I mean, at it’s most basic level. At first I thought it was simply a method to find a sum of numbers in an array. That is how I have used it before anyway. And yes, in it’s simplest form, it does perform this task as expected. But as time went on (within my incredible amount of experience), I started to see reduce() being used in a few different ways. So then the point of reduce() became lost on me.
  6.  
  7. But once I started breaking down the idea of reduce() into smaller pieces, it became more clear to me.
  8.  
  9. ## Let's break it down
  10.  
  11. What type of method is reduce() when used on an array? It is an iterator. You will have access to one element in the array at a time. Cool. What is the parameter for reduce()? It is a callback function. The iteration will perform a task or a set of tasks on one element at a time based on what we write within the call back function. What does .reduce() return? It returns a single value.
  12.  
  13. So what does all of this mean? Again, what is the point of .reduce()? The point is to iterate through each element in an array to perform a task on each element in order to reduce the elements into a SINGLE VALUE. Maybe we have an array of numbers. We can use .reduce() to iterate through each number and accumulate them together into one sum. Maybe we have an array of arrays. We can iterate through each array and accumulate them together one by one into one array. Maybe we have an array of objects. In that case, because of the iteration, we now have access to each object and it’s properties. Now we can pull out the information that we want, and combine each piece of information into a single value, whether that be a single object, a single array, a single number, what have you.
  14.  
  15. ## Example
  16.  
  17. Let’s look at our brewery example. In our getBeerCount function, we want to “return the total beer count of all beers for every brewery”. The long version I started with was this:
  18.  
  19. ```javascript
  20. let beerCountList = [];
  21. breweries.forEach(brewery => beerCountList.push(brewery.beers.length));
  22. console.log(beerCountList); // [ 12, 5, 9, 7, 7 ]
  23.  
  24. let numOfBeers = 0;
  25. beerCountList.forEach(num => numOfBeers += num);
  26. console.log(numOfBeers); // 40
  27. ```
  28.  
  29. However, because we gain access to each brewery’s properties when iterating through breweries, there is no reason to pull out information and store it as seen in beerCountList. So that code can be replaced with this code:
  30.  
  31. ```javascript
  32. let numOfBeers = 0;
  33. breweries.forEach(brewery => numOfBeers += brewery.beers.length);
  34. console.log(numOfBeers); // 40
  35. ```
  36.  
  37. Okay! So let’s break that chunk down a bit more to see how it is working:
  38.  
  39. ```javascript
  40. let numOfBeers = 0;
  41. breweries.forEach(brewery =>
  42. numOfBeers += brewery.beers.length);
  43. // Think of the above line as:
  44. // numOfBeers + brewery.beers.length = numOfBeers
  45. // So now, with each iteration we get:
  46. // 0 + 12 = 12
  47. // 12 + 5 = 17
  48. // 17 + 9 = 26
  49. // 26 + 7 = 33
  50. // 33 + 7 = 40
  51. console.log(numOfBeers); // 40
  52. ```
  53.  
  54. ## Accumulator Schmululator
  55.  
  56. You can think of numOfBeers as our accumulator. It is accumulating data with each iteration in our forEach(). The starting value of our accumulator was 0 but we are essentially reassigning value to numOfBeers with each iteration by combining the old value with some new data that we just accessed. Then, in the end, we have a single value stored in numOfBeers.
  57.  
  58. Wait, did I say accumulator? Isn’t that the thing we learned about when learning about the thing? Yes! It is a parameter of our call back function in reduce()! Keep in mind that the syntax for reduce() is:
  59.  
  60. `array.reduce(callback, initialValue)` with initialValue defaulting to the first element in the array if nothing is passed in.
  61.  
  62. The parameters of our callback are set to: `accumulator`, `currentValue`, `index` (optional), and `array` (optional)
  63.  
  64. SO. We can actually replace the previous code with:
  65.  
  66. ```javascript
  67. let numOfBeersResult = breweries.reduce((numOfBeers, brewery) => numOfBeers + brewery.beers.length, 0);
  68. console.log(numOfBeersResult); // 40
  69. ```
  70.  
  71. Because .reduce() returns a single value, we can store the code directly into a variable. And as you can see, we replaced our forEach() iterator with a reduce() iterator. And in the callback function, I passed in numOfBeers as the accumulator. I also passed in our starting value, 0, as a second argument after the callback. Tada!
  72.  
  73. ## Returning an Object?
  74.  
  75. But what if we want to return an object? We want to start with complex data, and want to access then combine parts of that data into one value, that value being a single object. Seems like a job for .reduce(), amiright?
  76.  
  77. Lets look at our cakes example. In groceryList() we want to make “an object where the keys are each topping, and the values are the amount of that topping I need to buy”.
  78.  
  79. One way to solve:
  80.  
  81. ```javascript
  82. let groceryList = {};
  83.  
  84. cakes.forEach(cake => {
  85. cake.toppings.forEach(topping => {
  86. if (!groceryList[topping]) {
  87. groceryList[topping] = 1;
  88. } else {
  89. groceryList[topping] ++;
  90. }
  91. });
  92. });
  93.  
  94. console.log(groceryList);
  95. // { 'dutch process cocoa': 1,
  96. 'toasted sugar': 3,
  97. 'smoked sea salt': 3,
  98. berries: 2,
  99. 'edible flowers': 2,
  100. mint: 1,
  101. cranberry: 1,
  102. 'crystallized ginger': 2 }
  103. ```
  104.  
  105. However, after looking at this, you can see that you have one starting value that accumulates data with each iteration in forEach() and outputs a new but still singular value at the end. So why not use .reduce()? And let’s throw a conditional operator in there just for fun.
  106.  
  107. ```javascript
  108. let groceryListResult = cakes.reduce((groceryList, cake) => {
  109. cake.toppings.forEach(topping => {
  110. !groceryList[topping] ? groceryList[topping] = 1 : groceryList[topping] ++;
  111. });
  112. return groceryList;
  113. }, {})
  114.  
  115. console.log(groceryListResult);
  116. // { 'dutch process cocoa': 1,
  117. 'toasted sugar': 3,
  118. 'smoked sea salt': 3,
  119. berries: 2,
  120. 'edible flowers': 2,
  121. mint: 1,
  122. cranberry: 1,
  123. 'crystallized ginger': 2 }
  124. ```
  125.  
  126. Instead of starting with a groceryList variable assigned to an empty object, we can use .reduce() and pass in groceryList as our accumulator in the callback function and pass the starting value of {} into .reduce() after the callback argument.
  127.  
  128. ## So... What did you say the point of .reduce() was?
  129.  
  130. This by no means a comprehensive guide to everything you can do with .reduce(). But I hope it helps offer some clarity on the concept.
  131.  
  132. So what is the point of .reduce()? At its most basic level, it is to reduce data into one single value.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement