เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่ใช้ประโยคเป็นอาร์กิวเมนต์แรกและตัวเดียว
ประโยคคือสตริงอักขระพิเศษที่มีช่องว่างจำนวนจำกัด
ฟังก์ชันควรจัดเรียงคำในประโยคใหม่โดยให้คำที่เล็กที่สุด (คำที่มีอักขระน้อยที่สุด) ปรากฏขึ้นก่อนแล้วตามด้วยคำที่ใหญ่กว่า
ตัวอย่างเช่น −
หากสตริงอินพุตเป็น −
const str = 'this is a string';
จากนั้นผลลัพธ์ควรเป็น −
const output = 'a is this string';
ตัวอย่าง
ต่อไปนี้เป็นรหัส -
const str = 'this is a string';
const arrangeWords = (str = []) => {
const data = str.toLowerCase().split(' ').map((val, i)=> {
return {
str: val,
length: val.length,
index: i
}
})
data.sort((a,b) => {
if (a.length === b.length)
return (a.index - b.index)
return (a.length - b.length)
});
let res = '';
let i = 0;
while (i < data.length - 1)
res += (data[i++].str + ' ');
res += data[i].str;
return (res)
};
console.log(arrangeWords(str)); ผลลัพธ์
ต่อไปนี้เป็นเอาต์พุตคอนโซล -
a is this string