เราได้รับสตริงที่มีคำซ้ำคั่นด้วยขีด (-)
const str = 'monday-sunday-tuesday-tuesday-sunday-sunday-monday-mondaymonday';
หน้าที่เขียนฟังก์ชันคืนอาร์เรย์อ็อบเจกต์ แต่ละอ็อบเจกต์มีคุณสมบัติ value และ count value คือคำในสตริง count คือจำนวนครั้งที่ปรากฏติดกัน
สำหรับสตริงข้างต้น อาร์เรย์จะเป็น
const arr = [
{ val: 'monday', count: 1 },
{ val: 'sunday', count: 1 },
{ val: 'tuesday', count: 2 },
{ val: 'sunday', count: 2 },
{ val: 'monday', count: 3 }
]
เพราะ monday ปรากฏ 1 ครั้ง แล้ว sunday 1 ครั้ง tuesday 2 ครั้ง sunday 2 ครั้ง และ monday 3 ครั้งสุดท้าย
เราจะ split อาร์เรย์ และใช้ Array.prototype.reduce() แบบ recursive คืนอาร์เรย์ที่ต้องการ
โค้ดเต็ม
ตัวอย่าง
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));
ผลลัพธ์
ผลลัพธ์ในคอนโซลจะเป็น
[
{ 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 }
]