Rearrange an array in maximum minimum form by JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

We are required to write a function, say minMax() that takes in an array of Numbers and rearranges the elements such that the greatest element appears first followed by the smallest elements then the second greatest element followed by second smallest element and so on.

For example −

// if the input array is:
const input = [1, 2, 3, 4, 5, 6, 7]
// then the output should be:
const output = [7, 1, 6, 2, 5, 3, 4]

So, let’s write the complete code for this function −

Example

const input = [1, 2, 3, 4, 5, 6, 7];
const minMax = arr => {
   const array = arr.slice();
   array.sort((a, b) => a-b);
   for(let start = 0; start < array.length; start += 2){
      array.splice(start, 0, array.pop());
   }
   return array;
};
console.log(minMax(input));

Output

The output in the console will be −

[
   7, 1, 6, 2,
   5, 3, 4
]
raja
Published on 26-Aug-2020 09:31:24
Advertisements