Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

การจัดเรียงตัวเลขขั้นต่ำและสตริงตามอักษรในอาร์เรย์ใน JavaScript

ปัญหา

เราต้องเขียนฟังก์ชัน JavaScript ที่รับอาร์เรย์ของตัวเลขและสตริง ฟังก์ชันควรคืนค่าอาร์เรย์เดียวที่มีตัวเลขเรียงจากน้อยไปมาก ตามด้วยสตริงเรียงตามลำดับอักษร ค่าต้องคงประเภทข้อมูลเดิม (type)

ตัวอย่าง

โค้ดตัวอย่างด้านล่าง:

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' ]

คำอธิบายเพิ่มเติม

Comparator function จัดการ 3 กรณี: number-string, string-number, string-string, number-number ใช้ localeCompare() แทน charCodeAt() จะดีกว่าสำหรับ Unicode