- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 ]
- Related Articles
- Minimum flips to make all 1s in left and 0s in right in C++
- Print n 0s and m 1s such that no two 0s and no three 1s are together in C Program
- Encoding a number string into a string of 0s and 1s in JavaScript
- Python - List Initialization with alternate 0s and 1s
- Count all 0s which are blocked by 1s in binary matrix in C++
- Constructing a string of alternating 1s and 0s of desired length using JavaScript
- How to handle right-to-left and left-to-right swipe gestures on Android?
- How to handle right-to-left and left-to-right swipe gestures on iOS App?
- XOR counts of 0s and 1s in binary representation in C++
- How to handle right-to-left and left-to-right swipe gestures on Android using Kotlin?
- Largest subarray with equal number of 0s and 1s in C++
- Finding the element larger than all elements on right - JavaScript
- Count Substrings with equal number of 0s, 1s and 2s in C++
- Maximum product of indexes of next greater on left and right in C++
- C Program to construct DFA accepting odd numbers of 0s and 1s

Advertisements