Dividing an array – JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

<p>Let&rsquo;s say, we are required to write a function that takes in an array arr of string / number literals as the first argument and a number n as second argument.</p><p>We are required to return an array of n subarrays, each of which contains at most arr.length / n elements. And the distribution of elements should be like this &minus;</p><ul class="list"><li>The first element goes in the first subarray, second in second, third in third and so on.</li><li>Once we have one element in each subarray, we again start with filling the first subarray with its second element.</li><li>Similarly, when all subarrays have two elements only after that we fill the third element in the first array and so on.</li></ul><p>For example &minus;</p><p>If the input array is &minus;</p><pre class="result notranslate">&nbsp; const input = [656, 756, 5345, 67, 43, 76, 54, 768, 34];</pre><p>And the number n is 3, then the output should be &minus;</p><pre class="result notranslate">const output = [ &nbsp; &nbsp;[ 656, 67, 54 ], &nbsp; &nbsp;[ 756, 43, 768 ], &nbsp; &nbsp;[ 5345, 76, 34 ] ];</pre><p>We will Array.prototype.reduce() method over the original array to construct the desired array.</p><h2>Example</h2><p>Following is the code &minus;</p><!---<p><a href="" target="_blank" rel="nofollow" class="demo"><i class="fa-external-link"></i> Live Demo</a></p>---><pre class="prettyprint notranslate">const input = [656, 756, 5345, 67, 43, 76, 54, 768, 34]; const divideArray = (arr, size) =&gt; { &nbsp; &nbsp;return arr.reduce((acc, val, ind) =&gt; { &nbsp; &nbsp; &nbsp; const subIndex = ind % size; &nbsp; &nbsp; &nbsp; if(!Array.isArray(acc[subIndex])){ &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;acc[subIndex] = [val]; &nbsp; &nbsp; &nbsp; }else{ &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;acc[subIndex].push(val); &nbsp; &nbsp; &nbsp; }; &nbsp; &nbsp; &nbsp; return acc; &nbsp; &nbsp;}, []); }; console.log(divideArray(input, 3));</pre><h2>Output</h2><p>This will produce the following output in console &minus;</p><pre class="result notranslate">[ [ 656, 67, 54 ], [ 756, 43, 768 ], [ 5345, 76, 34 ] ]</pre>
raja
Updated on 18-Sep-2020 12:27:30

Advertisements