
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Odd even sort in an array - 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];
Then the output should be −
const output = [2, 2, 6, 8, 1, 5, 7, 9];
Example
Following is the code −
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
Following is the output in the console −
[ 2, 2, 6, 8, 1, 5, 7, 9 ]
- Related Questions & Answers
- Python Program for Odd-Even Sort / Brick Sort
- C/C++ Program for Odd-Even Sort (Brick Sort)?
- C/C++ Program for the Odd-Even Sort (Brick Sort)?
- Odd even index difference - JavaScript
- Separate odd and even in JavaScript
- Determining sum of array as even or odd in JavaScript
- Count number of even and odd elements in an array in C++
- Java program to Print Odd and Even Number from an Array
- Absolute Difference of even and odd indexed elements in an Array (C++)?
- Adding only odd or even numbers JavaScript
- Find even odd index digit difference - JavaScript
- Sorting odd and even elements separately JavaScript
- Matching odd even indices with values in JavaScript
- How to find the Odd and Even numbers in an Array in java?
- Absolute Difference of even and odd indexed elements in an Array in C++?
Advertisements