{"id":4717,"date":"2018-06-22T10:53:38","date_gmt":"2018-06-22T10:53:38","guid":{"rendered":"https:\/\/tinjurewp.com\/jsblog\/?p=1656"},"modified":"2018-06-22T10:53:38","modified_gmt":"2018-06-22T10:53:38","slug":"learning-javascript-array-reduce-method","status":"publish","type":"post","link":"https:\/\/learncode.tinjurewp.com\/learning-javascript-array-reduce-method\/","title":{"rendered":"Learning JavaScript Array.Reduce() Method"},"content":{"rendered":"<p class=\"note icon-note\"><strong>Note<\/strong>: This post is work-in-progress learning-note and still in active development and updated regularly.<\/p>\n<p>In the previous posts,\u00a0<a href=\"https:\/\/tinjurewp.com\/jsblog\/understanding-javascript-arrays\/\" target=\"_blank\" rel=\"noopener\">Understanding JavaScript Arrays<\/a>\u00a0 and\u00a0<a href=\"https:\/\/tinjurewp.com\/jsblog\/learning-javascript-array-methods\/\" target=\"_blank\" rel=\"noopener\">Learning JavaScript Array Methods<\/a> were in detail. Because JS <code>array.reduce()<\/code> method is more complex and an important method, in this learning-post, we will discuss its basic syntax, how it works and explain with some examples.<\/p>\n<h3>Array.Reduce() Method<\/h3>\n<p>The <code>array.reduce()<\/code> method performs callback function once on each array elements (from left to right) reducing into a single value.<\/p>\n<h6 id=\"array-reduce-method-syntax\">Basic Syntax<\/h6>\n<pre class=\"line-numbers\"><code class=\"language-javascript\">\/\/without initial value\nlet reducer = arr.reduce(callback);\n\/\/callback function \nlet callbackName = function(accu, curVal, cumInd, arr) {\n  return accu + curr;\n });\n\n\/\/Arrow function syntax\nlet reducer = function(accu, curVal, cumInd, arr) =&gt; accu + curr;\n\n\/\/with intialValue (optional)\nlet reducer = arr.reduce(callback, initValue);\n\/\/callback function\nlet callbackName = function(accu, curVal, cumInd, arr) {\n  return accu + curr;\n }, iniValue);\n\n\/\/Arrow function syntax\nlet reducer = function(accu, curVal, cumInd, arr) =&gt; accu + curr, iniValue;<\/code><\/pre>\n<p>The <code>array.reduce()<\/code> method accepts two arguments: callback function (line 2) and an <em>optional<\/em> Initial Value (line 12). On MDN these<\/p>\n<ul>\n<li><code>reducer<\/code> : the single returned value by the <code>reduce()<\/code> call back function<\/li>\n<li><code>callback<\/code> : Function to execute on each element in the array, taking four arguments<\/li>\n<li><code>initialValue<\/code> : Value to use as the first argument to the first call of the <code>callback<\/code>. If no initial value is supplied, the first element in the array will be used.<\/li>\n<\/ul>\n<p>The callback function (lines 4-6) accepts four parameters:<\/p>\n<ul>\n<li><code>Accumuator<\/code> : The accumulator accumulates the callback&#8217;s return values; it is the accumulated value previously returned in the last invocation of the callback<\/li>\n<li><code>Current Value<\/code> : The current element being processed in the array.<\/li>\n<li><code>CurrentIndex<\/code> : the index of the current element being processed in the array. Starts at index 0, if an <code>initialValue<\/code> is provided, and at index 1 otherwise.<\/li>\n<li><code>Array<\/code> : The array <code>reduce()<\/code> was called upon (i.e. original array).<\/li>\n<\/ul>\n<p>To find the single <code>reducer<\/code> value (it could be named as sum or total) each iteration will add <code>currentValue<\/code> to <code>accumulator<\/code> value and return it. The returned value will be new <code>accumulator<\/code> and this process continues until the end of array. Once all the array elements are completed it will return as a single value assigned as <code>reducer<\/code>.<\/p>\n<h5>How reduce() works<\/h5>\n<p>Lets examine with a simple example (below) how <code>reduce()<\/code> method works:<\/p>\n<pre class=\"line-numbers\"><code class=\"language-javascript\">\/\/initialize numbers array\nlet num = [ 0, 1, 2, 3, 4 ];\n\/\/\nlet sum = num.reduce(function (accum, curValue) {\n  return accum + curValue;\n});\n\/\/OUTPUT\nconsole.log(sum); \/\/ =&gt; 10<\/code><\/pre>\n<p>The callback function is invoked four times with the arguments as shown below:<\/p>\n<table class=\"learnjs\">\n<thead>\n<tr>\n<th style=\"text-align: center;\">callback<\/th>\n<th style=\"text-align: center;\">accum<\/th>\n<th style=\"text-align: center;\">curValue<\/th>\n<th style=\"text-align: center;\">curIndex<\/th>\n<th style=\"text-align: center;\">array<\/th>\n<th style=\"text-align: center;\">sum<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>First Call<\/td>\n<td style=\"text-align: center;\">0<\/td>\n<td style=\"text-align: center;\">1<\/td>\n<td style=\"text-align: center;\">1<\/td>\n<td style=\"text-align: center;\"><code>[0, 1, 2, 3, 4]<\/code><\/td>\n<td style=\"text-align: center;\">1<\/td>\n<\/tr>\n<tr>\n<td>2nd Call<\/td>\n<td style=\"text-align: center;\">1<\/td>\n<td style=\"text-align: center;\">2<\/td>\n<td style=\"text-align: center;\">2<\/td>\n<td style=\"text-align: center;\"><code>[0, 1, 2, 3, 4]<\/code><\/td>\n<td style=\"text-align: center;\">3<\/td>\n<\/tr>\n<tr>\n<td>3rd Call<\/td>\n<td style=\"text-align: center;\">3<\/td>\n<td style=\"text-align: center;\">3<\/td>\n<td style=\"text-align: center;\">3<\/td>\n<td style=\"text-align: center;\"><code>[0, 1, 2, 3, 4]<\/code><\/td>\n<td style=\"text-align: center;\">6<\/td>\n<\/tr>\n<tr>\n<td>4th Call<\/td>\n<td style=\"text-align: center;\">6<\/td>\n<td style=\"text-align: center;\">4<\/td>\n<td style=\"text-align: center;\">4<\/td>\n<td style=\"text-align: center;\"><code>[0, 1, 2, 3, 4]<\/code><\/td>\n<td style=\"text-align: center;\">10<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>In the first call, <code>accumulator<\/code> is the initial value (first argument) which is 0, and current value, which is first array) is 1 and its return value (0 + 1) is 1. In the next call, the return of the previous call becomes the first argument (<code>accumulator<\/code>) and so on. For the 2nd call, its initial value of <code>accumulator<\/code> is 1, its current value (second element) is 2 so 1 + 2 = 3, its return value is 3. In the last (4th) run, initial value for <code>accumulator<\/code> is 6 and its current value is 4, which is added and returns final value as 10.<\/p>\n<h4>Some Use Case Examples<\/h4>\n<p>The following use case examples are adopted from <em>Josh Pitzalis<\/em>&#8216;s article <a href=\"https:\/\/medium.freecodecamp.org\/reduce-f47a7da511a9\" target=\"_blank\" rel=\"noopener\">How JavaScript\u2019s Reduce method works, when to use it, and some of the cool things it can\u00a0do<\/a>.<\/p>\n<h6>Finding an Average<\/h6>\n<p>The <code>Array.reduce()<\/code> method can be used to find an <code>average<\/code> by dividing the <code>total<\/code> value with the length of the array and returning a <em>final<\/em> value.<\/p>\n<pre class=\"line-numbers\"><code class=\"language-javascript\">\/\/initialize number array\nconst num = [10, 15, 20, 25, 50];\n\/\/ Initialize reduce method with arrow function\nconst average = num.reduce((total, amount, index, array) =&gt; {\n  total += amount;\n  if( index === array.length-1) { \n    return total\/array.length;\n  }else { \n    return total;\n  }\n});\n\/\/access average value\nconsole.log(average); \/\/ OUTPUT =&gt; 24<\/code><\/pre>\n<p>In the example above, the <em>index<\/em> argument (line 4) is used in <code>if..else<\/code> loop to iterate over the array and returning itself in the last argument.<\/p>\n<h6>Creating A Tally<\/h6>\n<p>The following example, adapted from the <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Global_Objects\/Array\/Reduce#Counting_instances_of_values_in_an_object\" target=\"_blank\" rel=\"noopener\">MDN Reference Document<\/a>, is used to count instances values (or tally) of each item in a collection of an array.<\/p>\n<pre class=\"line-numbers\"><code class=\"language-javascript\">\/\/ initialize cars array\nlet cars = [&#039;Toyota&#039;, &#039;Ford&#039;, &#039;Honda&#039;, &#039;Toyota&#039;, &#039;BMW&#039;];\n\/\/initialize CarCounts with reduce method\nvar carCounts = cars.reduce(function (allCars, car) { \n  if (car in allCars) {\n    allCars[car]++;\n  }\n  else {\n    allCars[car] = 1;\n  }\n  return allCars;\n}, {});\n\n\/\/re-writing carCounts using arrow function syntax\nconst carCounts = cars.reduce( (allCars, car) =&gt; {\n  allCars[car] = (allCars[car] || 0) + 1 ;\n  return allCars;\n} , {})\n\n\/\/Access carCounts value\ncarCounts; \/\/OUTPUT =&gt; {Toyota: 2, Ford: 1, Honda: 1, BMW: 1}<\/code><\/pre>\n<p>In the example above, <code>array.reduce()<\/code> is used to tally <code>cars<\/code> (or count occurrence of each car) using a basic (lines: 4-12) or an arrow function (14-18) which is assigned to a <code>carCounts<\/code> variable. In this case, the initial value must be empty <code>{}<\/code> object (lines: 12, 18).<\/p>\n<h6>Flattening an Array<\/h6>\n<p>The <code>Array.reduce()<\/code> can also be used to flatten nested arrays into a single array.<\/p>\n<pre class=\"line-numbers\"><code class=\"language-javascript\">\/\/ initialize car arrays\nlet carArrays = [[&quot;Camry&quot;, &quot;Corolla&quot;], [&quot;Fusion&quot;], [&quot;Civic&quot;, &quot;Hybrid&quot;]];\n\/\/initilize allVehicles using reduce method\nlet allVehicles = carArrays.reduce(function(accum, curVal) {\n    return accum.concat(curVal);\n   },\n  [] ); \/\/initial value an empty array\n\/\/ access allVehicles\nallVehicles; \/\/OUTPUT =&gt; [&quot;Camry&quot;, &quot;Corolla&quot;, &quot;Fusion&quot;, &quot;Civic&quot;, &quot;Hybrid&quot;] \n\n\/\/re-writing with ES6 Arrow Function syntax \nlet allVehicles = carArrays.reduce(\n  ( accum, curVal ) =&gt; accum.concat(curVal),\n  [] \/\/ initial value an empty array\n);\n\/\/ access allVehicles\nallVehicles; \/\/OUTPUT =&gt;[&quot;Camry&quot;, &quot;Corolla&quot;, &quot;Fusion&quot;, &quot;Civic&quot;, &quot;Hybrid&quot;]<\/code><\/pre>\n<p>In the example above, <code>carArrays<\/code> is initialized with three nested arrays with car names as array items (line 2). Using <code>Array.reduce()<\/code> method, the three arrays were combined into a single array <code>allVehicles<\/code> by first, setting initial value as empty (lines: 7, 14) and then concatenating current value <code>curVal<\/code> to the total value <code>accum<\/code> (lines: 5, 13).<\/p>\n<p class=\"tip icon-tip\"><strong>Tip<\/strong>: Additional use case <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Global_Objects\/Array\/Reduce#Examples\" target=\"_blank\" rel=\"noopener\">examples<\/a> of <code>&lt;a href=&quot;https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Global_Objects\/Array\/Reduce&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;Array.reduce()&lt;\/a&gt;<\/code> are described on the Mozilla Developer Network.<\/p>\n<h5>Wrapping Up<\/h5>\n<p>In previous learning-note post <a href=\"https:\/\/tinjurewp.com\/jsblog\/learning-javascript-array-methods\/\" target=\"_blank\" rel=\"noopener\">Learning JavaScript Array Methods<\/a>, different built-in array methods were discussed. Because the <code>&lt;a href=&quot;https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Global_Objects\/Array\/Reduce&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;Array.reduce()&lt;\/a&gt;<\/code> method is an important JS methods is used in performing various task, such as flattening arrays, tallying array items etc, it was discussed separately. In this posts basic <code>array.reduce()<\/code> method syntax, how it works including its parameters are discussed.<\/p>\n<p>Related Post : <a href=\"https:\/\/tinjurewp.com\/jsblog\/learning-javascript-array-methods\/\" target=\"_blank\" rel=\"noopener\">Learning JavaScript Array Methods<\/a><\/p>\n<h5>Useful Resources &amp; Links<\/h5>\n<p>While preparing this post, I have referred the following references extensively. Visit original link for additional information.<\/p>\n<ul>\n<li><a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Global_Objects\/Array\/reduce\" target=\"_blank\" rel=\"noopener\">Array .prototype .reduce()<\/a> | <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\" target=\"_blank\" rel=\"noopener\">MDN JavaScript Reference<\/a><\/li>\n<li><a href=\"https:\/\/hackernoon.com\/reduce-your-fears-about-array-reduce-629b334ab945\" target=\"_blank\" rel=\"noopener\">Reduce your fears about Array.reduce()<\/a> &#8211; by <em>Dave Lunny<\/em> | Hackernoon<\/li>\n<li><a href=\"https:\/\/codeburst.io\/learn-understand-javascripts-reduce-function-b2b0406efbdc\" target=\"_blank\" rel=\"noopener\">Learn &amp; Understand JavaScript\u2019s Reduce Function<\/a> | codeburst.io<\/li>\n<li><a href=\"https:\/\/medium.freecodecamp.org\/reduce-f47a7da511a9\" target=\"_blank\" rel=\"noopener\">How JavaScript\u2019s Reduce method works, when to use it, and some of the cool things it can do<\/a> &#8211; by <em>Josh Pitzalis<\/em> | freeCodeCamp<\/li>\n<li><a href=\"https:\/\/www.sitepoint.com\/map-reduce-functional-javascript\/\" target=\"_blank\" rel=\"noopener\">Using Map and Reduce in Functional JavaScript<\/a> &#8211; by <em>M. David Green<\/em> | SitePoint<\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>Note: This post is work-in-progress learning-note and still in active development and updated regularly. In the previous posts,\u00a0Understanding JavaScript Arrays\u00a0 and\u00a0Learning JavaScript Array Methods were in detail. Because JS array.reduce() method is more complex and an important method, in this learning-post, we will discuss its basic syntax, how it works and explain with some examples. [&hellip;]<\/p>\n","protected":false},"author":3,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_crdt_document":"","footnotes":""},"categories":[47,4],"tags":[],"class_list":["post-4717","post","type-post","status-publish","format-standard","hentry","category-arrays","category-javascript"],"_links":{"self":[{"href":"https:\/\/learncode.tinjurewp.com\/wp-json\/wp\/v2\/posts\/4717","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/learncode.tinjurewp.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/learncode.tinjurewp.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/learncode.tinjurewp.com\/wp-json\/wp\/v2\/users\/3"}],"replies":[{"embeddable":true,"href":"https:\/\/learncode.tinjurewp.com\/wp-json\/wp\/v2\/comments?post=4717"}],"version-history":[{"count":0,"href":"https:\/\/learncode.tinjurewp.com\/wp-json\/wp\/v2\/posts\/4717\/revisions"}],"wp:attachment":[{"href":"https:\/\/learncode.tinjurewp.com\/wp-json\/wp\/v2\/media?parent=4717"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/learncode.tinjurewp.com\/wp-json\/wp\/v2\/categories?post=4717"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/learncode.tinjurewp.com\/wp-json\/wp\/v2\/tags?post=4717"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}