# Sorting an array of binary values - JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

#### JavaScript for beginners

Best Seller

74 Lectures 10 hours

#### Modern Javascript for Beginners + Javascript Projects

Most Popular

112 Lectures 15 hours

#### The Complete Full-Stack JavaScript Course!

Best Seller

96 Lectures 24 hours

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
]
Updated on 18-Sep-2020 09:50:37