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

การจัดเรียงอัลฟา-ตัวเลขด้วย JavaScript

เรามีอาร์เรย์ผสมที่ต้องจัดเรียงตามตัวอักษรแล้วตามตัวเลข:

const arr = ['Ab-1', 'Ab-11', 'Ab-12', 'ab-10', 'ab-100', 'ab-101', 'ab2', 'ab-3', 'ab-105'];

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

โค้ดสำหรับทำสิ่งนี้คือ:

const arr = ['Ab-1', 'Ab-11', 'Ab-12', 'ab-10', 'ab-100', 'ab-101', 'ab2', 'ab-3', 'ab-105'];
const alphaNumericSort = (arr = []) => {
  arr.sort((a, b) => {
    const aPart = a.split('-');
    const bPart = b.split('-');
    return aPart[0].toLowerCase().localeCompare(bPart[0].toLowerCase()) || aPart[1] - bPart[1];
  });
};
alphaNumericSort(arr);
console.log(arr);

ผลลัพธ์

ผลลัพธ์ในคอนโซลจะเป็นดังนี้:

[
  'Ab-1', 'ab-2',
  'ab-3', 'ab-10',
  'Ab-11', 'Ab-12',
  'ab-100', 'ab-101',
  'ab-105'
]