Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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
]
How It Works
The function creates a copy of the original array using slice(). It then iterates through the array:
- When it finds a
0, it removes it usingsplice()and adds it to the end withpush() - When it finds a
1, it removes it and adds it to the beginning withunshift() - Other numbers remain in their relative positions
Alternative Approach Using Filter
const segregateWithFilter = arr => {
const ones = arr.filter(num => num === 1);
const others = arr.filter(num => num !== 0 && num !== 1);
const zeros = arr.filter(num => num === 0);
return [...ones, ...others, ...zeros];
};
const testArr = [3, 2, 1, 8, 9, 0, 1, 9, 0, 2, 1, 0];
console.log(segregateWithFilter(testArr));
[1, 1, 1, 3, 2, 8, 9, 9, 2, 0, 0, 0]
Conclusion
Both approaches successfully segregate 0s and 1s while preserving other numbers. The filter method is more readable, while the splice approach modifies the array in-place during iteration.
Advertisements
