{"id":205,"date":"2019-12-15T07:19:34","date_gmt":"2019-12-15T07:19:34","guid":{"rendered":"https:\/\/www.samarthya.me\/wps\/?p=205"},"modified":"2019-12-15T07:19:34","modified_gmt":"2019-12-15T07:19:34","slug":"js-reduce-and-foreach","status":"publish","type":"post","link":"https:\/\/blog.samarthya.me\/wps\/2019\/12\/15\/js-reduce-and-foreach\/","title":{"rendered":"JS Reduce and forEach"},"content":{"rendered":"<p><img fetchpriority=\"high\" decoding=\"async\" class=\"aligncenter  wp-image-206\" src=\"https:\/\/www.samarthya.me\/wps\/wp-content\/uploads\/2019\/12\/IMG_20160902_171750-300x169.jpg\" alt=\"Matrix\" width=\"385\" height=\"217\" srcset=\"https:\/\/blog.samarthya.me\/wps\/wp-content\/uploads\/2019\/12\/IMG_20160902_171750-300x169.jpg 300w, https:\/\/blog.samarthya.me\/wps\/wp-content\/uploads\/2019\/12\/IMG_20160902_171750-1024x576.jpg 1024w, https:\/\/blog.samarthya.me\/wps\/wp-content\/uploads\/2019\/12\/IMG_20160902_171750-768x432.jpg 768w, https:\/\/blog.samarthya.me\/wps\/wp-content\/uploads\/2019\/12\/IMG_20160902_171750-1536x864.jpg 1536w, https:\/\/blog.samarthya.me\/wps\/wp-content\/uploads\/2019\/12\/IMG_20160902_171750-2048x1152.jpg 2048w\" sizes=\"(max-width: 385px) 100vw, 385px\" \/><\/p>\n<p>I have been polishing my Go and JS skills recently and today learned about how to use the <a href=\"https:\/\/www.w3schools.com\/jsref\/jsref_reduce.asp\">reduce<\/a>() and <a href=\"https:\/\/www.w3schools.com\/jsref\/jsref_foreach.asp\">forEach<\/a>() method. The problem I was trying to solve was return columns and rows from an input string.<\/p>\n<blockquote><p>A new line separator is used to define a new row and for each element is separated by &#8216; &#8216;.<\/p><\/blockquote>\n<p>I started off with a basic class (code below)<\/p>\n<div>\n<pre>export class Matrix {\r\n  constructor(matrix) {}\r\n}<\/pre>\n<p>The matrix is the input string that we shall be using to populate <strong>rows<\/strong> and <strong>columns.<\/strong><\/p>\n<h2>Parsing<\/h2>\n<h3>Rows<\/h3>\n<div>\n<pre>this.rows = matrix.split('\\n')\r\n      .map(row =&gt; row.split(' ')\r\n      .map(r =&gt; +r));<\/pre>\n<p>Parsing rows was relatively simple, I used the map method to find individual element and convert it to a number. (Numeric representation), if numeric is not required a simple split should do.<\/p>\n<h3>Columns<\/h3>\n<div>\n<pre>1.  this.columns = this.rows.reduce(\r\n2.  (columns, row, i) =&gt; {\r\n3.   row.forEach((current, j) =&gt; {\r\n4.   if (i===0) {\r\n5.    columns.push([row[j]]);\r\n6.   } else {\r\n7.    columns[j].push(current);\r\n8.   }\r\n9.  });\r\n10.  return columns;\r\n11. }, []);<\/pre>\n<p>In row 1. I simply invoked <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Global_Objects\/Array\/reduce\">reduce()<\/a> method on rows which we parsed in the step above.<\/p>\n<p>The <strong>reducer<\/strong> function takes four arguments:<\/p>\n<ol>\n<li>Accumulator (acc)<\/li>\n<li>Current Value (cur)<\/li>\n<li>Current Index (idx)<\/li>\n<li>Source Array (src)<\/li>\n<\/ol>\n<p>Your <strong>reducer<\/strong> function&#8217;s returned value is assigned to the accumulator, whose value is remembered across each iteration throughout the array and ultimately becomes the final, single resulting value.<\/p>\n<pre>(columns, row, i)<\/pre>\n<\/div>\n<p>We intent to return the columns which shall have the individual column read from the array of rows. Each &#8216;row&#8217; will be representation of one such row [ ] and &#8216;i&#8217; is the index.<\/p>\n<\/div>\n<pre>If there are 3 rows that were read. e.g. [0,1,2],[3,4,5],[5,6,7] the i will iterate through 0..2<\/pre>\n<p>For each row that we get in step 2, we will iterate through the individual elements within that row to be added to column array (<a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Global_Objects\/Array\/forEach\">forEach<\/a>).<\/p>\n<p>forEach is taking two arguments<\/p>\n<pre>(current, j)\r\nCurrent -&gt; Identifies the value being processed.\r\nj       -&gt; Identifies the index.<\/pre>\n<p>The processing is done between line 4 &#8211; 8.<\/p>\n<p>So if we consider an example<\/p>\n<pre>    0 1 2\r\n--------------\r\n0 | 1 2 3 \\n\r\n1 | 4 5 6 \\n\r\n2 | 7 8 9 \\n<\/pre>\n<p>So the rows get populated as<\/p>\n<pre>row = [\r\n    rows[0] = [1, 2, 3]\r\n    rows[1] = [4, 5, 6]\r\n    rows[2] = [7, 8, 9]\r\n]<\/pre>\n<p>So, the processing of line 4 &#8211; 8<\/p>\n<pre>row +&gt; 1, 2 ,3 &amp; i =0\r\nThe first iteration starts at\r\ncurrent = 1, j = 0\r\n\r\nLine 4. since i = 0\r\ncolumns[0] = 1\r\nThe loop repeats\r\ncolumns[1] = 2\r\nThe loop repeats\r\ncolumns [2] = 3\r\nThe outer loop repeats\r\nrow +&gt; 4, 5 ,6 &amp; i =1\r\ncurrent = 4, j = 0\r\n\r\n&amp; the same way the logic repeats.<\/pre>\n<p>Finally you will have <em><strong>columns<\/strong><\/em><\/p>\n<pre>columns = [[1,4,7], [2, 5, 8], [3, 6, 9]]<\/pre>\n<p style=\"text-align: center;\">&#8211; THE &#8211; END &#8211;<\/p>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>I have been polishing my Go and JS skills recently and today learned about how to use the reduce() and forEach() method. The problem I was trying to solve was return columns and rows from an input string. A new line separator is used to define a new row and for each element is separated [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_exactmetrics_skip_tracking":false,"_exactmetrics_sitenote_active":false,"_exactmetrics_sitenote_note":"","_exactmetrics_sitenote_category":0,"footnotes":""},"categories":[1],"tags":[22,19],"class_list":["post-205","post","type-post","status-publish","format-standard","hentry","category-others","tag-array","tag-js"],"_links":{"self":[{"href":"https:\/\/blog.samarthya.me\/wps\/wp-json\/wp\/v2\/posts\/205","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/blog.samarthya.me\/wps\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blog.samarthya.me\/wps\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blog.samarthya.me\/wps\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/blog.samarthya.me\/wps\/wp-json\/wp\/v2\/comments?post=205"}],"version-history":[{"count":0,"href":"https:\/\/blog.samarthya.me\/wps\/wp-json\/wp\/v2\/posts\/205\/revisions"}],"wp:attachment":[{"href":"https:\/\/blog.samarthya.me\/wps\/wp-json\/wp\/v2\/media?parent=205"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blog.samarthya.me\/wps\/wp-json\/wp\/v2\/categories?post=205"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blog.samarthya.me\/wps\/wp-json\/wp\/v2\/tags?post=205"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}