Sorting an array of binary values - JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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
]
raja
Published on 18-Sep-2020 13:20:37
Advertisements