ปัญหา
เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่รับอาร์เรย์ของตัวเลขและสตริง ฟังก์ชันของเราควรจะส่งคืนอาร์เรย์เดียวที่มีการเรียงลำดับตัวเลขจากน้อยไปหามากก่อน ตามด้วยสตริงที่เรียงลำดับตามตัวอักษร
ค่าต่างๆ จะต้องคงไว้ซึ่งรูปแบบเดิม
ตัวอย่าง
ต่อไปนี้เป็นรหัส -
const arr = [5, 8, 'car', 'dad', 'amber', 1, 12, 76, 'bat'];
const separateSort = (arr = []) => {
const sorter = (a, b) => {
if(typeof a === 'number' && typeof b === 'string'){
return -1;
};
if(typeof a === 'string' && typeof b === 'number'){
return 1;
};
if(typeof a === 'string' && typeof b === 'string'){
return a.charCodeAt(0) - b.charCodeAt(0);
};
return a - b;
};
const res = arr.sort(sorter);
return res;
};
console.log(separateSort(arr)); ผลลัพธ์
ต่อไปนี้เป็นเอาต์พุตคอนโซล -
[ 1, 5, 8, 12, 76, 'amber', 'bat', 'car', 'dad' ]