- 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
Segregate all 0s on right and 1s on left in JavaScript
We have an array of Numbers that contains 0, 1 and some other numbers. We are required to write a JavaScript function that takes in this array and brings all 1s to the start and 0s to the end
Let's write the code for this function −
Example
const arr = [3, 2, 1, 8, 9, 0, 1, 9, 0, 2, 1, 0, 2, 0, 1, 0, 1, 1, 4, 0, 3]; const segregate = arr => { const copy = arr.slice(); for(let i = 0; i < copy.length; i++){ if(copy[i] === 0){ copy.push(copy.splice(i, 1)[0]); }else if(copy[i] === 1){ copy.unshift(copy.splice(i, 1)[0]); }; continue; }; return copy; }; console.log(segregate(arr));
Output
The output in the console will be −
[ 1, 1, 1, 3, 2, 8, 9, 1, 9, 2, 2, 1, 1, 4, 3, 0, 0, 0, 0, 0, 0 ]
Advertisements