{"id":3322,"date":"2022-07-31T10:07:59","date_gmt":"2022-07-31T15:07:59","guid":{"rendered":"https:\/\/www.becomebetterprogrammer.com\/?p=3322&#038;preview=true&#038;preview_id=3322"},"modified":"2022-07-31T10:15:01","modified_gmt":"2022-07-31T15:15:01","slug":"javascript-array-reduce","status":"publish","type":"post","link":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-array-reduce\/","title":{"rendered":"How to use Array Reduce in JavaScript: A Complete Guide"},"content":{"rendered":"\n<p class=\"language-javascript\">The Array Object in Javascript supports several methods that you can use to manipulate the array elements. These include the <code>array.map()<\/code>, <a href=\"https:\/\/www.becomebetterprogrammer.com\/javascript-array-sort\/\"><code>array.sort()<\/code><\/a>, <code>array.filter()<\/code>, <code>array.reduce()<\/code> etc. The latter &#8211; <code>array.reduce()<\/code> method &#8211; is regarded as one of the most tricky array methods and can be quite hard to understand at first glance. However, it\u2019s a powerful method and is a key component of functional programming in Javascript.<\/p>\n\n\n\n<p class=\"language-javascript\"><strong>The <code>array.reduce()<\/code> method is a built-in Javascript method that reduces all the elements in an array to a single value while preserving the original array. That single value can be of any type &#8211; string, number, object, etc.<\/strong><\/p>\n\n\n\n<p class=\"language-javascript\">This post will provide a comprehensive guide on the <code>Array.reduce()<\/code> method in JavaScript. We will look at its syntax, properties, and several examples in code to help you understand the concept better. We will also give you an insight into the <code>Array.reduceRight()<\/code> method, which works similarly to the <code>Array.reduce()<\/code> method.<\/p>\n\n\n\n<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_82_2 counter-hierarchy ez-toc-counter ez-toc-custom ez-toc-container-direction\">\n<div class=\"ez-toc-title-container\"><p class=\"ez-toc-title\" style=\"cursor:inherit\">Table of Contents<\/p>\n<\/div><nav><ul class='ez-toc-list ez-toc-list-level-1 ' ><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-array-reduce\/#Introduction_to_the_Arrayreduce_Method_in_Javascript\" >Introduction to the Array.reduce() Method in Javascript<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-array-reduce\/#The_Arrayreduce_Method_Syntax\" >The Array.reduce() Method Syntax<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-array-reduce\/#The_Callback_Function_in_Arrayreduce_Method\" >The Callback Function in Array.reduce() Method&nbsp;<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-array-reduce\/#The_Initial_Value_Argument\" >The Initial Value Argument<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-array-reduce\/#Understanding_the_Arrayreduce_Logic\" >Understanding the Array.reduce() Logic<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-6\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-array-reduce\/#The_ES5_version_of_the_Arrayreduce_Method\" >The ES5 version of the Array.reduce() Method.<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-7\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-array-reduce\/#The_ES6_version_of_the_Arrayreduce_Method\" >The ES6 version of the Array.reduce() Method<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-8\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-array-reduce\/#Arrayreduce_Method_Examples\" >Array.reduce() Method Examples<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-9\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-array-reduce\/#Example_1_Get_the_Sum_of_Elements_in_an_Array\" >Example 1: Get the Sum of Elements in an Array<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-10\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-array-reduce\/#Example_2_Summing_Values_in_an_Object\" >Example 2: Summing Values in an Object<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-11\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-array-reduce\/#Example_3_Grouping_Items_with_the_Same_Values\" >Example 3: Grouping Items with the Same Values<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-12\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-array-reduce\/#Example_4_Counting_the_Instances_of_an_Item_in_an_Array\" >Example 4: Counting the Instances of an Item in an Array<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-13\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-array-reduce\/#Example_5_Reducing_an_Array_of_Arrays\" >Example 5: Reducing an Array of Arrays<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-14\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-array-reduce\/#Example_6_Remove_Duplicate_Items\" >Example 6: Remove Duplicate Items<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-15\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-array-reduce\/#The_ArrayreduceRight_Method\" >The Array.reduceRight() Method<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-16\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-array-reduce\/#Common_Mistakes_to_Avoid\" >Common Mistakes to Avoid<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-17\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-array-reduce\/#Conclusion\" >Conclusion<\/a><\/li><\/ul><\/nav><\/div>\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Introduction_to_the_Arrayreduce_Method_in_Javascript\"><\/span>Introduction to the <code>Array.reduce()<\/code> Method in Javascript<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Let\u2019s look at the array of numbers below.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>const numbers = &#91;1,2,3,4,5]<\/code><\/pre>\n\n\n\n<p class=\"language-javascript\">We can use various methods to get the sum of all the elements in the array. Let\u2019s start with the <code>forEach()<\/code> method in Javascript.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>const numbers = &#91;1,2,3,4,5]\nlet sum = 0\nfor(let item of numbers){\n   sum = sum + item\n}\nconsole.log(sum)\n\/\/Result: 15<\/code><\/pre>\n\n\n\n<p class=\"language-javascript\">Here, we are using a pretty simple algorithm. First, we declare a variable called \u2018<em>sum\u2019<\/em> and initialized it to zero (0). Using the <code>forEach()<\/code> method, we loop over the array and get each array item one by one as we add it to <em>\u2018sum\u2019<\/em> after every iteration. In simple terms, we reduced our array to a single value. In this case, a number<\/p>\n\n\n\n<p class=\"language-javascript\">Even though this method helped us achieve what we wanted, there is a more cleaner and elegant method that we can use &#8211; the <code>Array.reduce()<\/code> method.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>const numbers = &#91;1,2,3,4,5]\nconst sum = numbers.reduce(function(accumulator, initialValue){\n  return accumulator + initialValue\n},0)\nconsole.log(sum)\n\/\/Result: 15<\/code><\/pre>\n\n\n\n<p class=\"language-javascript\">That looks pretty simple. Right? Well, let\u2019s look at the <code>Array.reduce()<\/code> method in detail.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"The_Arrayreduce_Method_Syntax\"><\/span>The <code>Array.reduce()<\/code> Method Syntax<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p class=\"language-javascript\">The <code>array.reduce()<\/code> method takes two arguments &#8211; a callback function and an initial value.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>array.reduce(callbackFunction&#91;, initialValue]);<\/code><\/pre>\n\n\n\n<p>Let\u2019s have an in-depth look at these two arguments.<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>The callback function argument<\/li><li>The initialValue argument<\/li><\/ul>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"The_Callback_Function_in_Arrayreduce_Method\"><\/span>The Callback Function in <code>Array.reduce()<\/code> Method&nbsp;<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p class=\"language-javascript\">The <code>Array.reduce()<\/code> method invokes the callback function on every item in the array. That callback function also takes four arguments &#8211; <em>accumulator\/total<\/em>, <em>currentValue<\/em>, <em>currentIndex<\/em> and <em>array<\/em>. Therefore, another way we could write the <code>Array.reduce()<\/code> syntax is shown below.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>array.reduce(function(accumulator, currentValue, currentIndex, array), initialValue)<\/code><\/pre>\n\n\n\n<ul class=\"language-javascript wp-block-list\"><li><code>accumulator<\/code>: This is a required argument and is also known as \u2018<em>total<\/em>.\u2019 It holds the <em>initialValue<\/em> when the callback function is first invoked. In the other successive calls, the accumulator always holds the last value returned by the callback function. <br><br>If an <em>initialValue<\/em> is not provided, the accumulator uses the first array element (index zero) as the <em>initialValue<\/em>.<\/li><li><code>currentValue<\/code>: This is also a required argument that holds the currently executed element of the array. When the callback function is first invoked, the currentValue holds the first element of the array (index zero). <br><br>However, if an <em>initialValue<\/em> was not provided, it holds the array&#8217;s second element (index one).<\/li><li><code>currentIndex<\/code>: This is an optional argument and can be omitted. It stores the index of the <em>currentValue<\/em> in the array. When the callback function is first invoked, it is always set to index zero (first array element) if an initialValue was provided. Otherwise, it will be set to index one (second array element)<\/li><li><code>array<\/code>: This is also an optional argument and can be omitted. It holds the complete array that the reduce() method works on.<\/li><\/ul>\n\n\n\n<p>You can learn more about callback functions in our post \u201c<a href=\"https:\/\/www.becomebetterprogrammer.com\/javascript-callback-functions\/\">The Ultimate Guide to Callback Functions in JavaScript<\/a>.\u201d&nbsp;<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"The_Initial_Value_Argument\"><\/span>The Initial Value Argument<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>This is an &#8220;<em>optional<\/em>&#8221; argument that holds the first value passed to the callback function. If this value is not provided, the callback function will use the first element (index zero) of the array as the <em>initialValue<\/em>.<\/p>\n\n\n\n<p class=\"language-javascript has-vivid-green-cyan-background-color has-background\"><strong>Tip<\/strong>: Here, we are using the word optional in quotes because there are certain <code>Array.reduce()<\/code> programs that would not work without an <em>initialValue<\/em>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Understanding_the_Arrayreduce_Logic\"><\/span>Understanding the <code>Array.reduce()<\/code> Logic<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>The table below shows you the logic that is used when you pass\/ not pass an initialValue.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td><strong>initialValue<\/strong><\/td><td><strong>Accumulator<\/strong><\/td><td><strong>currentValue<\/strong><\/td><td><strong>currentIndex<\/strong><\/td><\/tr><tr><td>Passed<\/td><td>initialValue<\/td><td>The first element of the array.<\/td><td>The first element of the array.<\/td><\/tr><tr><td>Not passed<\/td><td>The first element of the array<\/td><td>The second element of the array<\/td><td>The first element of the array.<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"language-javascript\">Now that you have a good understanding of the <code>Array.reduce()<\/code> method, let\u2019s have an in-depth look at the code above where we were getting the sum of all array elements.&nbsp;<\/p>\n\n\n\n<p class=\"has-vivid-green-cyan-background-color has-background\"><strong>Tip<\/strong>: We have tweaked the code a little so that we can see what is happening step-by-step.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>const numbers = &#91;2,3,4]\nconst log = console.log\nconst sum = numbers.reduce(function(accumulator, currentValue){\n  log(`accumulator_Value = ${accumulator}`)\n  log(`currentValue = ${currentValue}`)\n  return accumulator + currentValue\n},0)\nconsole.log(`Total Sum = ${sum}`)<\/code><\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>\/\/First Call\naccumulator_Value = 0 \/\/same as initialValue\ncurrentValue = 2\n\n\/\/Second Call\naccumulator_Value = 2\ncurrentValue = 3\n\n\/\/Third Call\naccumulator_Value = 5\ncurrentValue = 4\n\nTotal Sum = 9<\/code><\/pre>\n\n\n\n<p>Explanation:<\/p>\n\n\n\n<p>When the callback function was first invoked, the accumulator had a value of zero (0) which is the <em>initialValue<\/em> that we passed. The <em>currentValue<\/em> on the other hand had a value of \u20182\u2019 which is the first element of the array. The callback function did a sum of the <em>accumulator<\/em> value and <em>currentValue<\/em> (0 + 2) and this result was stored in the <em>accumulator<\/em>.<\/p>\n\n\n\n<p>In the second iteration, the <em>accumulator<\/em> had a value of \u20182\u2019, and the <em>currentValue<\/em> now held the second item of the array \u20183.\u2019 Again, the function did a sum of the <em>accumulator<\/em> value and the <em>currentValue<\/em> (2 + 3), and this value was stored in the <em>accumulator<\/em>. This process goes on and on until the reduce method has looped through all the elements in the array.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"The_ES5_version_of_the_Arrayreduce_Method\"><\/span>The ES5 version of the <code>Array.reduce()<\/code> Method.<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>As you might know, Javascript conforms to the <a href=\"https:\/\/www.w3schools.com\/js\/js_versions.asp\" target=\"_blank\" rel=\"noopener\">ECMAScript specifications<\/a>. As of writing this post, the most popular editions in the developer&#8217;s community are Javascript ES5 (2009) and Javascript ES6 (2015).<\/p>\n\n\n\n<p>All the code we have written up to this point conforms to the ES5 edition. In ES5, we need to have parentheses and a return statement when writing functions as shown in the code below.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>const numbers = &#91;item,item,item,item,item]\nconst sum = numbers.reduce(function(accumulator, initialValue){\n  return accumulator + initialValue\n},0)<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"The_ES6_version_of_the_Arrayreduce_Method\"><\/span>The ES6 version of the <code>Array.reduce()<\/code> Method<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>The ES6 edition introduces the use of Arrow functions in Javascript. Let\u2019s convert the code above to use arrow functions.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>const numbers = &#91;item,item,item,item,item]\nconst sum = numbers.reduce((accumulator, item)=&gt;(accumulator + item),0)<\/code><\/pre>\n\n\n\n<p>Alternatively, you can include the <em>\u2018return\u2019<\/em> statement by adding parentheses as shown below.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>const sum = numbers.reduce((accumulator, item)=&gt;{\n  return accumulator + item\n},0)<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Arrayreduce_Method_Examples\"><\/span>Array.reduce() Method Examples<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p class=\"language-javascript\">Up to this point, we have had a good understanding of the <code>Array.reduce()<\/code> method syntax and its logic. Let\u2019s now have a look at more examples to better understand the concept.<\/p>\n\n\n\n<p class=\"has-vivid-green-cyan-background-color has-background\"><strong>Tip<\/strong>: Most of the examples that we will look at in this post will make use of the Arrow function syntax.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Example_1_Get_the_Sum_of_Elements_in_an_Array\"><\/span>Example 1: Get the Sum of Elements in an Array<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>Let\u2019s take an array of student marks as shown below.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>const marks = &#91;56,58,63,72,80]<\/code><\/pre>\n\n\n\n<p class=\"language-javascript\">To get the total marks using the <code>Array.reduce()<\/code> method, we will write the code as shown below.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>const sum = marks.reduce((accumulator, arrayItems)=&gt;(accumulator + arrayItems),0)\nconsole.log(sum)<\/code><\/pre>\n\n\n\n<p>That was quite easy, right? We are iterating through the elements in the array and adding them to the accumulator. Let\u2019s look at more complex examples where we have an array of objects.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Example_2_Summing_Values_in_an_Object\"><\/span>Example 2: Summing Values in an Object<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>Let&#8217;s take a look at the array of objects below.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>let person =&#91;\n{name:\"Karen\", age:24, hobby:\"dancing\"},\n{name:\"John Doe\", age:23, hobby:\"riding\"},\n{name:\"Nikita\", age:15, hobby:\"drawing\"},\n{name:\"Jane\", age:24, hobby:\"swimming\"},\n{name:\"Benn\", age:23, hobby:\"travelling\"},\n]<\/code><\/pre>\n\n\n\n<p>To get the \u2018sum\u2019 of all ages in the array, we will write our code as shown below.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>const sum = person.reduce((accumulator, arrayItem) => {\n   return accumulator + arrayItem.age\n},0)\nconsole.log(sum)\/\/Result: 109<\/code><\/pre>\n\n\n\n<p class=\"language-javascript\">Here we are using a pretty straightforward logic. We first initialize the accumulator to zero (0) and then iterate through the \u2018<em>person array<\/em>\u2019 to fetch an element starting with index zero. <\/p>\n\n\n\n<p class=\"language-javascript\">We then retrieve the age value from this element (<code>arrayItem.age<\/code>) and add it to the accumulator. This loop continues until we have fetched every item from the array.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Example_3_Grouping_Items_with_the_Same_Values\"><\/span>Example 3: Grouping Items with the Same Values<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p class=\"language-javascript\">The <code>Array.reduce()<\/code> method also comes quite in handy when you want to group items with the same values. For example, let\u2019s group the people who have the same age in the \u2018<em>person array<\/em>.\u2019 We should end up with a list like;<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>{15: &#91;person_1,person_2]}<\/code><\/pre>\n\n\n\n<p>We will write our code as follows.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>const groupedByAge = person.reduce((accumulator, arrayItem)=>{\n  let age = arrayItem.age\n  if(accumulator&#91;age] == null) accumulator&#91;age] = &#91;]\n  accumulator&#91;age].push(arrayItem.name)\n  return accumulator\n},{})\nconsole.log(groupedByAge)<\/code><\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>{15:&#91;\"Nikitah\"],\n23:&#91;\"John Doe\", \"Benn\"],\n24:&#91;\"Karen\", \"Jane\"]}<\/code><\/pre>\n\n\n\n<p class=\"language-javascript\">In this example, you will notice that we are reducing our array into an object. We start by initializing our initialValue as an empty object (<code>{}<\/code>). Next, we declare a variable \u2018age\u2019 that stores the \u2018age value\u2019 from the fetched from the array element (<code>let age = arrayItem.age<\/code>).<\/p>\n\n\n\n<p>We then write an \u2018<em>if statement<\/em>\u2019 that checks whether the accumulator (which holds our <em>initialValue<\/em> at the first iteration) has an item equal to that age. If it doesn\u2019t have that item, we assign the item an empty array where it will add people of that age.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Example_4_Counting_the_Instances_of_an_Item_in_an_Array\"><\/span>Example 4: Counting the Instances of an Item in an Array<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>This example is slightly similar to Example 3. Here, we want to calculate the instance of an item in an array.<\/p>\n\n\n\n<p>Let\u2019s use the array of laptop brands below.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>const laptops = &#91;\"Dell\",\"HP\",\"Dell\",\"Toshiba\",\"Toshiba\",\"Apple\"]<\/code><\/pre>\n\n\n\n<p>We will write our code as shown below.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>const instances = laptops.reduce((accumulator, currentValue)=>{\n   if (accumulator&#91;currentValue] == null) { accumulator&#91;currentValue] = 1 }\n   else {\n     accumulator&#91;currentValue] +=1\n   }\n   return(accumulator)\n},{})\nconsole.log(instances)\n\/\/Result:{Dell:2,HP:1,Toshiba:2,Apple:1}<\/code><\/pre>\n\n\n\n<p>Here, we first set our <em>initialValue<\/em> to an empty object. Next, we write an \u2018if statement\u2019 that checks whether the <em>currentValue<\/em> is already in the <em>accumulator<\/em>. If the <em>currentValue<\/em> is not in the <em>accumulator<\/em>, we add this value and set it to 1 which is the current laptop brand. However, if the <em>currentValue<\/em> is already in the <em>accumulator<\/em>, we add 1 to its existing value.<\/p>\n\n\n\n<p>See the logic below:<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>\/\/First Iteration\naccumulatorValue ={} \/\/The accumulator is an empty object same as initialValue\ncurrentValue = \"Dell\" \/\/adds value to accumulator\naccumulatorValue {Dell:1}\n\n\/\/Second IterationaccumulatorValue ={Dell:1}\ncurrentValue = \"HP\" \/\/adds value to accumulator\naccumulatorValue {Dell:1, HP:1}\n\n\/\/Third IterationaccumulatorValue ={Dell:1, HP:1}\ncurrentValue = \"Dell\" \/\/adds value to accumulator\naccumulatorValue {Dell:2, HP:1}\n\n\/\/Fourth IterationaccumulatorValue ={Dell:1, HP:1}\ncurrentValue = \"Toshiba\"\naccumulatorValue {Dell:2, HP:1, Toshiba:1}\n\n\/\/This loop continues until we have iterated through all elements in the array.<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Example_5_Reducing_an_Array_of_Arrays\"><\/span>Example 5: Reducing an Array of Arrays<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>What if you have an array inside an array and you wish to reduce the entire array to a single value? <\/p>\n\n\n\n<p>Let\u2019s have a look at the example below.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>Const pointsArray = &#91;&#91;2,3],&#91;4,5],9,&#91;7,8]]<\/code><\/pre>\n\n\n\n<p class=\"language-javascript\">&nbsp;To reduce this array to a single array, we will use the <code>Array.reduce()<\/code> method together with the <code>concat()<\/code> method as shown below.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>const reducedArray= pointsArray.reduce((accumulator, currentValue)=>{\n   return accumulator.concat(currentValue)\n},&#91;])\nconsole.log(reducedArray)\n\/\/Result\n&#91;2, 3, 4, 5, 9, 7, 8]<\/code><\/pre>\n\n\n\n<p class=\"language-javascript\">Since we want to reduce our <em>\u2018pointsArray\u2019<\/em> to an array, we will set the initial value to an empty array (<code>[ ]<\/code>). We then use the <code>concat()<\/code> method which concatenates\/ joins the elements (<em>currentValue<\/em>) we fetch from the array during each iteration.<\/p>\n\n\n\n<p>Our short program uses the logic below.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>\/\/First Iteration\naccumulatorValue =&#91;] \/\/The accumulator is an empty array same as the initialValue\ncurrentValue = &#91;2,3] \/\/add to accumulator\naccumulatorValue &#91;2,3]\n\n\/\/Second Iteration\naccumulatorValue =&#91;2,3]\ncurrentValue = &#91;4,5] \/\/add to accumulator\naccumulatorValue &#91;2,3,4,5]\n\n\/\/Third Iteration\naccumulatorValue =&#91;2,3]\ncurrentValue = &#91;9] \/\/add to accumulator\naccumulatorValue &#91;2,3,4,5,9]\n\n\/\/This loop continues until we have iterated through all elements in the array.<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Example_6_Remove_Duplicate_Items\"><\/span>Example 6: Remove Duplicate Items<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p class=\"language-javascript\">Another scenario where you can apply the <code>Array.reduce()<\/code> method is when you want to remove duplicate items from an array. Take a look at the array of numbers below.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>const repeatedNums=&#91;1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9]<\/code><\/pre>\n\n\n\n<p class=\"language-javascript\">To remove all duplicate numbers in this array, we can use the <code>Array.reduce()<\/code> method shown below.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>const reducedArray = repeatedNums.reduce((acc, curr)=>{\n  if(acc.includes(curr) === true){}   \n  else{\n    acc.push(curr)\n  }\n  return acc\n},&#91;])console.log(reducedArray)\n\/\/Result: &#91; 1, 2, 3, 4, 5, 6, 7, 8, 9 ]<\/code><\/pre>\n\n\n\n<p>Here, we first set our <em>initialValue<\/em> to an empty array. We then loop through the array and fetch an item. Next, we use a conditional statement to check whether this item is already in the <em>accumulator<\/em>. If it&#8217;s already in the <em>accumulator<\/em>, we do nothing, however, if it\u2019s not, we add it to the accumulator.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"The_ArrayreduceRight_Method\"><\/span>The <code>Array.reduceRight()<\/code> Method<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p class=\"language-javascript\">The <code>Array.reduceRight()<\/code> works just like the <code>Array.reduce()<\/code> method with only one difference.<\/p>\n\n\n\n<ul class=\"language-javascript wp-block-list\"><li>The <code>Array.reduce()<\/code> method loops through an Array starting from the first (index zero) element to the last.<\/li><li>The <code>Array.reduceRight()<\/code> method loops through the array starting from the last element to the first.<\/li><\/ul>\n\n\n\n<p>Let\u2019s understand this better in code.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>\/\/Array.reduce() Method\n\nconst arr = &#91;1,2,3,4,5]\nconst loopItems = arr.reduce((acc, curr)=&gt;{\n    console.log(curr)\n    return acc\n},0)\/\/Result: 1,2,3,4,5<\/code><\/pre>\n\n\n\n<p class=\"language-javascript\">From the output above, you can see that the <code>Array.reduce()<\/code> method looped through the array starting with the first time to the last.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>\/\/Array.reduceRight() Method\n\nconst arr = &#91;1,2,3,4,5]\nconst loopItems = arr.reduceRight((acc, curr)=&gt;{\n    console.log(curr)\n    return acc\n},0)\/\/Result: 5,4,3,2,1<\/code><\/pre>\n\n\n\n<p class=\"language-javascript\">From the output above, you can see the <code>Array.reduceRight()<\/code> method looped through the array starting with the last item to the first.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Common_Mistakes_to_Avoid\"><\/span>Common Mistakes to Avoid<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<ul class=\"language-javascript wp-block-list\"><li>Always remember to pass the <em>initialValue<\/em> of the <code>Array.reduce()<\/code> method, unless you are 100% sure you wouldn\u2019t need it in your program.<\/li><li>Don\u2019t forget the \u2018<em>return<\/em>\u2019 statement especially if you have parentheses in your callback function. If you don\u2019t, you will keep getting the error \u201c<em>accumulator is undefined<\/em>.\u201d Also, double-check your code to ensure you are returning the right value.<\/li><\/ul>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Conclusion\"><\/span>Conclusion<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p class=\"language-javascript\">This post has given you a comprehensive guide on the <code>Array.reduce()<\/code> method and how to use it to reduce an array to a single value. We have also looked at the <code>Array.reduceRight()<\/code> method which works similarly to the <code>Array.reduce()<\/code> method.<\/p>\n\n\n\n<p><strong>Was this article helpful?<\/strong><\/p>\n\n\n\n<p class=\"language-javascript\">Share it with other developers who want an in-depth explanation of the <code>Array.reduce()<\/code> method. You can also share your thoughts by replying on Twitter of <a href=\"https:\/\/twitter.com\/bbprogrammer\/status\/1459150572565798916\" target=\"_blank\" rel=\"noopener\">Become A Better Programmer<\/a> or to <a href=\"https:\/\/twitter.com\/NetmattaTech\" target=\"_blank\" rel=\"noopener\">my personal account<\/a>.<\/p>\n\n\n\n<figure class=\"wp-block-embed aligncenter is-type-rich is-provider-twitter wp-block-embed-twitter\"><div class=\"wp-block-embed__wrapper\">\n<blockquote class=\"twitter-tweet\" data-width=\"550\" data-dnt=\"true\"><p lang=\"en\" dir=\"ltr\">Quick <a href=\"https:\/\/twitter.com\/hashtag\/javascript?src=hash&amp;ref_src=twsrc%5Etfw\" target=\"_blank\" rel=\"noopener\">#javascript<\/a> question!<br><br>Is the initialValue in the method array.reduce required or optional?<br><br>Find out the answer in this complete guide about the array.reduce method by Billy Samuel (<a href=\"https:\/\/twitter.com\/NetmattaTech?ref_src=twsrc%5Etfw\" target=\"_blank\" rel=\"noopener\">@NetmattaTech<\/a> ) <a href=\"https:\/\/t.co\/p6egOIgHdf\">https:\/\/t.co\/p6egOIgHdf<\/a><\/p>&mdash; Become A Better Programmer (@bbprogrammer) <a href=\"https:\/\/twitter.com\/bbprogrammer\/status\/1553761036272123904?ref_src=twsrc%5Etfw\" target=\"_blank\" rel=\"noopener\">July 31, 2022<\/a><\/blockquote><script async src=\"https:\/\/platform.twitter.com\/widgets.js\" charset=\"utf-8\"><\/script>\n<\/div><\/figure>\n","protected":false},"excerpt":{"rendered":"<p>The Array Object in Javascript supports several methods that you can use to manipulate the array elements. These include the array.map(), array.sort(), array.filter(), array.reduce() etc. The latter &#8211; array.reduce() method &#8211; is regarded as one of the most tricky array methods and can be quite hard to understand at first glance. However, it\u2019s a powerful &#8230; <a title=\"How to use Array Reduce in JavaScript: A Complete Guide\" class=\"read-more\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-array-reduce\/\" aria-label=\"More on How to use Array Reduce in JavaScript: A Complete Guide\">Read more<\/a><\/p>\n","protected":false},"author":5,"featured_media":3367,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"nf_dc_page":"","_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[16],"tags":[],"class_list":["post-3322","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-javascript","generate-columns","tablet-grid-50","mobile-grid-100","grid-parent","grid-50"],"_links":{"self":[{"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/posts\/3322","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/users\/5"}],"replies":[{"embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/comments?post=3322"}],"version-history":[{"count":5,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/posts\/3322\/revisions"}],"predecessor-version":[{"id":3370,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/posts\/3322\/revisions\/3370"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/media\/3367"}],"wp:attachment":[{"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/media?parent=3322"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/categories?post=3322"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/tags?post=3322"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}