
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Rearrange Array in Maximum Minimum Form by JavaScript
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 ]
Advertisements