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
]

Updated on: 18-Sep-2020

367 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements