- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Uneven sorting of array in JavaScript
Problem
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 −
arr[0] < arr[1] > arr[2] < arr[3]....
For example, if the input to the function is −
const arr = [1, 5, 1, 1, 6, 4];
Then the output can (there can be more than one possible answer as well) be −
const output = [2, 3, 1, 3, 1, 2];
Example
The code for this will be −
const arr = [1, 5, 1, 1, 6, 4]; const unevenSort = (arr = []) => { arr.sort((a, b) => a - b); let mid = Math.floor(arr.length / 2); if(arr.length % 2 === 1){ mid += 1; }; let even = arr.slice(0, mid); let odd = arr.slice(mid); for(let i = 0; i < arr.length; i++){ if(i % 2 === 0){ arr[i] = even.pop(); }else{ arr[i] = odd.pop(); }; }; }; unevenSort(arr); console.log(arr);
Output
The output in the console will be −
[ 1, 6, 1, 5, 1, 4 ]
- Related Articles
- Sorting parts of array separately in JavaScript
- Alternative sorting of an array in JavaScript
- Sorting an array of binary values - JavaScript
- Sorting an array of objects by an array JavaScript
- JavaScript array sorting by level
- Sorting Array based on another array JavaScript
- Sorting Array with JavaScript reduce function - JavaScript
- Sorting Array without using sort() in JavaScript
- Sorting an array by date in JavaScript
- Sorting an array by price in JavaScript
- Sorting JavaScript object by length of array properties.
- Sorting only a part of an array JavaScript
- Sorting array of Number by increasing frequency JavaScript
- Sorting digits of all the number of array - JavaScript
- Sorting an array of literals using quick sort in JavaScript

Advertisements