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

วิธีแยกตัวอักษรและตัวเลขจากอาร์เรย์โดยใช้ JavaScript

เรามีอาร์เรย์ที่มีตัวเลขและสตริงปนกัน ต้องเขียนฟังก์ชันเรียงแยกสองชนิด และแต่ละชนิดต้องเรียงในตัวเองด้วย

โค้ดฟังก์ชันเรียง

ตัวอย่าง

const arr = [1, 5, 'fd', 6, 'as', 'a', 'cx', 43, 's', 51, 7];
const sorter = (a, b) => {
  const first = typeof a === 'number';
  const second = typeof b === 'number';
  if(first && second){
    return a - b;
  }else if(first && !second){
    return -1;
  }else if(!first && second){
    return 1;
  }else{
    return a > b ? 1 : -1;
  }
};
arr.sort(sorter);
console.log(arr);

ผลลัพธ์

ผลลัพธ์ในคอนโซลจะเป็น

[ 1, 5, 6, 7, 43, 51, 'a', 'as', 'cx', 'fd', 's' ]