
- 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
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 Questions & Answers
- 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
- Even numbers at even index and odd numbers at odd index in C++
- Odd even sort in an array - JavaScript
- How to separate even and odd numbers in an array by using for loop in C language?
- Signals and Systems: Even and Odd Signals
- Adding only odd or even numbers JavaScript
- Find even odd index digit difference - JavaScript
- Matching odd even indices with values in JavaScript
- Even and Odd Components of a Signal
- Odd Even Jump in C++
- Sum of individual even and odd digits in a string number using JavaScript
Advertisements