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
]

Updated on: 31-Aug-2020

138 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements