ปัญหา
เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่ใช้สตริงคำ str ฟังก์ชันของเราจำเป็นต้องส่งคืนอาร์เรย์ของคำ จัดเรียงตามตัวอักษรตามอักขระสุดท้ายในแต่ละคำ
หากคำสองคำมีตัวอักษรตัวสุดท้ายเหมือนกัน อาร์เรย์ที่ส่งคืนควรแสดงตามลำดับที่ปรากฏในสตริงที่กำหนด
ตัวอย่าง
ต่อไปนี้เป็นรหัส -
const str = 'this is some sample string';
const sortByLast = (str = '') => {
const arr = str.split(' ');
const sorter = (a, b) => {
return a[a.length - 1].charCodeAt(0) - b[b.length - 1].charCodeAt(0);
};
arr.sort(sorter);
const sortedString = arr.join(' ');
return sortedString;
};
console.log(sortByLast(str)); ผลลัพธ์
ต่อไปนี้เป็นเอาต์พุตคอนโซล -
some sample string this is