ปัญหา
เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่รับสตริงที่มีสตริงไบนารีที่มีความยาว 3 คั่นด้วยช่องว่าง
ฟังก์ชันของเราควรเรียงลำดับตัวเลขจากน้อยไปมาก แต่เรียงลำดับเฉพาะเลขคู่และปล่อยเลขคี่ทั้งหมดไว้แทน
ตัวอย่าง
ต่อไปนี้เป็นรหัส -
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)); ผลลัพธ์
101 111 100 001 010