How to use Reverse Iteration Approach In Javascript
Here, in this approach 1 we will initially sort the given or input array in the descending order (high-low). Later, we iterate through the sorted descending order array and then palace the largest value element at the even indices and the rest elements are at odd indices in the result array.
Example: In this example, we are using Reverse Iteration Approach in JavaScript
Javascript
//Using Reverse Iteration function rearrangeArrayUsingReverseIteration(arrayInput) { const n = arrayInput.length; const descSortedArray = arrayInput .slice() .sort((a, b) => b - a); const rearrangedArray = []; for (let i = 0; i < n; i++) { if (i % 2 === 0) { rearrangedArray[i] = descSortedArray.pop(); } else { rearrangedArray[i] = descSortedArray.shift(); } } return rearrangedArray; } const inputArray = [2, 4, 3, 5, 6]; const rearrangedArray = rearrangeArrayUsingReverseIteration(inputArray); console.log(rearrangedArray); |
[ 2, 6, 3, 5, 4 ]
JavaScript Program to Rearrange Array such that Even Positioned are Greater than Odd
In this article, we will cover rearranging array such that even positions are greater than odd in JavaScript.
Give there is an array that we need to rearrange in the pattern where the even positioned are greater than the odd positioned in JavaScript. We will see the code for each approach along with the output. Below are the possible approaches that will be discussed in this article:
Example: