Uneven sorting of array in JavaScript

JavascriptWeb DevelopmentFront End Technology

<h2>Problem</h2><p>We are required to write a JavaScript function that takes in an array of numbers, arr, as the only argument. Our function should sort this array in such a way that after sorting, the elements should follow this pattern &minus;</p><pre class="result notranslate">arr[0] &lt; arr[1] &gt; arr[2] &lt; arr[3]....</pre><p>For example, if the input to the function is &minus;</p><pre class="result notranslate">const arr = [1, 5, 1, 1, 6, 4];</pre><p>Then the output can (there can be more than one possible answer as well) be &minus;</p><pre class="result notranslate">const output = [2, 3, 1, 3, 1, 2];</pre><h2>Example</h2><p>The code for this will be &minus;</p><pre class="prettyprint notranslate">const arr = [1, 5, 1, 1, 6, 4]; const unevenSort = (arr = []) =&gt; { &nbsp; &nbsp;arr.sort((a, b) =&gt; a - b); &nbsp; &nbsp;let mid = Math.floor(arr.length / 2); &nbsp; &nbsp;if(arr.length % 2 === 1){ &nbsp; &nbsp; &nbsp; mid += 1; &nbsp; &nbsp;}; &nbsp; &nbsp;let even = arr.slice(0, mid); &nbsp; &nbsp;let odd = arr.slice(mid); &nbsp; &nbsp;for(let i = 0; i &lt; arr.length; i++){ &nbsp; &nbsp; &nbsp; if(i % 2 === 0){ &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;arr[i] = even.pop(); &nbsp; &nbsp; &nbsp; }else{ &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;arr[i] = odd.pop(); &nbsp; &nbsp; &nbsp; }; &nbsp; &nbsp;}; }; unevenSort(arr); console.log(arr);</pre><h2>Output</h2><p>The output in the console will be &minus;</p><pre class="result notranslate">[ 1, 6, 1, 5, 1, 4 ]</pre>
raja
Updated on 20-Mar-2021 05:29:41

Advertisements