Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Sắp xếp từ trong chuỗi theo độ dài tăng dần - JavaScript

Viết hàm sắp xếp các từ trong chuỗi theo độ dài tăng dần.

Ví dụ

Chuỗi: 'This is a sample string only'

Độ dài: This(4), is(2), a(1), sample(6), string(6), only(4)

Kết quả: 'a is This only sample string'

Giải pháp

Mã triển khai:

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

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

console.log(arrangeByLength(str));

Kết quả

Đầu ra trong console:

a is This only sample string

Lưu ý: sort ổn định (stable) từ ES2019, từ cùng độ dài giữ thứ tự gốc.