
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
Separate odd and even in JavaScript
We are required to write a JavaScript function that takes in an array of numbers and returns an array with all even numbers appearing on the left side of any odd number and all the odd numbers appearing on the right side of any even number.
Therefore, let's write the code for this function −
Example
const arr = [2, 6, 3, 7, 8, 3, 5, 4, 3, 6, 87, 23, 2, 23, 67, 4]; 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 0; }; arr.sort(sorter); console.log(arr);
Output
The output in the console will be −
[ 2, 6, 8, 4, 6, 2, 4, 3, 7, 3, 5, 3, 87, 23, 23, 67 ]
- Related Articles
- Separate Odd and Even Elements into Two Separate Arrays in Java
- C program to store even, odd and prime numbers into separate files
- Sorting odd and even elements separately JavaScript
- Odd even index difference - JavaScript
- Add class (odd and even) in HTML via JavaScript?
- Swapping even and odd index pairs internally in JavaScript
- Odd even sort in an array - JavaScript
- Even numbers at even index and odd numbers at odd index in C++
- Matching odd even indices with values in JavaScript
- How to separate even and odd numbers in an array by using for loop in C language?
- Adding only odd or even numbers JavaScript
- Find even odd index digit difference - JavaScript
- Determining sum of array as even or odd in JavaScript
- What are even and odd numbers?
- Sum of individual even and odd digits in a string number using JavaScript

Advertisements