- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Special type of sort of array of numbers in JavaScript
We are required to write a JavaScript function that takes in an array of numbers and sorts the array such that first all the even numbers appear in ascending order and then all the odd numbers appear in ascending order.
For example: If the input array is −
const arr = [2, 5, 2, 6, 7, 1, 8, 9];
Output
Then the output should be −
const output = [2, 2, 6, 8, 1, 5, 7, 9];
Therefore, let’s write the code for this function −
Example
The code for this will be −
const arr = [2, 5, 2, 6, 7, 1, 8, 9]; const isEven = num => num % 2 === 0; const sorter = ((a, b) => { if(isEven(a) && !isEven(b)){ return -1; }; if(!isEven(a) && isEven(b)){ return 1; }; return a - b; }); const oddEvenSort = arr => { arr.sort(sorter); }; oddEvenSort(arr); console.log(arr);
Output
The output in the console will be −
[ 2, 2, 6, 8, 1, 5, 7, 9 ]
Advertisements