Cho chuỗi từ phân cách bằng '-', nén thành mảng object {val, count} đếm lần xuất hiện liên tiếp.
Ví dụ:
const str = 'monday-sunday-tuesday-tuesday-sunday-sunday-monday-mondaymonday';
Kết quả:
const arr = [{ val: 'monday', count: 1 }, { val: 'sunday', count: 1 }, { val: 'tuesday', count: 2 }, { val: 'sunday', count: 2 }, { val: 'monday', count: 3 }]Dùng split('-') và reduce() so sánh với phần tử cuối mảng kết quả.
Ví dụ
const str = 'monday-sunday-tuesday-tuesday-sunday-sunday-monday-mondaymonday'; const str2 = 'friday-friday-sunday-tuesday-sunday-sunday-monday-thursdaymonday'; const compressString = (str) => { return str.split('-').reduce((acc, val) => { const { length: l } = acc; if(acc[l-1]?.val === val){ acc[l-1].count++; return acc; }else{ return acc.concat({ val, count: 1 }); } }, []); } console.log(compressString(str)); console.log(compressString(str2));Kết quả
Đầu ra console:
[ { val: 'monday', count: 1 }, { val: 'sunday', count: 1 }, { val: 'tuesday', count: 2 }, { val: 'sunday', count: 2 }, { val: 'monday', count: 3 } ] [ { val: 'friday', count: 2 }, { val: 'sunday', count: 1 }, { val: 'tuesday', count: 1 }, { val: 'sunday', count: 2 }, { val: 'monday', count: 1 }, { val: 'thursday', count: 1 }, { val: 'monday', count: 1 } ]