ปัญหา
เราต้องเขียนฟังก์ชัน JavaScript ที่รับอาร์เรย์ของสตริง ฟังก์ชันควรลบตัวอักษรซ้ำที่ปรากฏติดกันในสตริงและคืนค่าอาร์เรย์สตริงที่แก้ไขแล้ว
ตัวอย่าง
โค้ดตัวอย่างด้านล่าง:
const arr = ["kelless", "keenness"];
const removeConsecutiveDuplicates = (arr = []) => {
const map = [];
const res = [];
arr.map(el => {
el.split('').reduce((acc, value, index, arr) => {
if (arr[index] !== arr[index + 1]) {
map.push(arr[index]);
}
if (index === arr.length - 1) {
res.push(map.join(''));
map.length = 0;
}
}, 0);
});
return res;
};
console.log(removeConsecutiveDuplicates(arr));
ผลลัพธ์
[ 'keles', 'kenes' ]
คำอธิบายเพิ่มเติม
"kelless" → k e l l e s s → ลบ l ซ้ำ, s ซ้ำ → "keles" / "keenness" → k e e n n e s s → ลบ e ซ้ำ, n ซ้ำ, s ซ้ำ → "kenes" โค้ดใช้ reduce ตรวจสอบ arr[index] !== arr[index+1]