Sort Binary String with Even Decimal Value Using JavaScript



Problem

We are required to write a JavaScript function that takes in a string that contains binary strings of length 3 all separated by spaces.

Our function should sort the numbers in ascending order but only order the even numbers and leave all odd numbers in their place.

Example

Following is the code −

 Live Demo

const str = '101 111 100 001 010';
const sortEvenIncreasing = (str = '') => {
   const sorter = (a, b) => {
      const findInteger = bi => parseInt(bi, 2);
      if(findInteger(a) % 2 === 1 || findInteger(b) % 2 === 1){
         return 0;
      };
      return findInteger(a) - findInteger(b);
   };
   const res = str
   .split(' ')
   .sort(sorter)
   .join(' ');
   return res;
};
console.log(sortEvenIncreasing(str));

Output

101 111 100 001 010
Updated on: 2021-04-21T06:49:07+05:30

160 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements