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

การจัดเรียงคำในสตริงตามความยาว - JavaScript

จัดเรียงคำในประโยคตามความยาวจากน้อยไปมาก

ตัวอย่าง

Input:  'This is a sample string only'
Output: 'a is This only sample string'

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

const str = 'This is a sample string only';

const arrangeByLength = str => {
  return str.split(' ')
    .sort((a, b) => a.length - b.length)
    .join(' ');
};

console.log(arrangeByLength(str));

ผลลัพธ์

a is This only sample string

หมายเหตุ: sort ไม่เสถียร (unstable) คำที่ความยาวเท่ากันอาจสลับลำดับ