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