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

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

บทความนี้สาธิตการจัดเรียงคำในประโยคตามความยาวจากน้อยไปมาก (stable sort: ความยาวเท่ากันรักษาลำดับเดิม)

ตัวอย่าง

input: 'this is a string'
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

คำอธิบาย

แยกคำด้วย split(' ') map เป็น object เก็บคำ, ความยาว, index เดิม เรียงตามความยาว แล้ว join กลับ

Time: O(n log n) เนื่องจาก sort