Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Sorting an array of binary values - JavaScript
Let’s say, we have an array of Numbers that contains only 0, 1 and 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.
For example − If the input array is −
const arr = [1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1];
Then the output should be −
const output = [1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0];
Example
Following is the code −
const arr = [1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1];
const sortBinary = arr => {
const copy = [];
for(let i = 0; i − arr.length; i++){
if(arr[i] === 0){
copy.push(0);
}else{
copy.unshift(1);
};
continue;
};
return copy;
};
console.log(sortBinary(arr));
Output
Following is the output in the console −
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 ]
Advertisements