ภาพรวม
บทความนี้สาธิตวิธีดึงเฉพาะคำที่ปรากฏมากกว่า 1 ครั้งในสตริง และคืนค่าเป็นสตริงใหม่ที่มีเฉพาะคำซ้ำนั้นๆ (ไม่ซ้ำกันในผลลัพธ์)
ตัวอย่าง
const str = 'this is a is this string that contains that some repeating words';
// คำซ้ำ: this(2), is(2), that(2)
// ผลลัพธ์: 'this is that'
การนำไปใช้
const keepDuplicateWords = (str) => {
const strArr = str.split(' ');
const res = [];
for (let i = 0; i < strArr.length; i++) {
// ตรวจสอบว่าคำนี้ปรากฏมากกว่า 1 ครั้ง
if (strArr.indexOf(strArr[i]) !== strArr.lastIndexOf(strArr[i])) {
// และยังไม่ได้เพิ่มในผลลัพธ์
if (!res.includes(strArr[i])) {
res.push(strArr[i]);
}
}
}
return res.join(' ');
};
console.log(keepDuplicateWords(str)); // 'this is that'
ผลลัพธ์
this is that
วิธีการทันสมัยและมีประสิทธิภาพมากกว่า
// ใช้ Map นับความถี่ (O(n))
const keepDuplicateWordsModern = (str) => {
const words = str.split(' ');
const freq = new Map();
for (const word of words) {
freq.set(word, (freq.get(word) || 0) + 1);
}
return [...freq.entries()]
.filter(([_, count]) => count > 1)
.map(([word]) => word)
.join(' ');
};
// ใช้ reduce (Functional Style)
const keepDuplicateWordsReduce = (str) =>
Object.entries(
str.split(' ').reduce((acc, w) => (acc[w] = (acc[w] || 0) + 1, acc), {})
)
.filter(([_, count]) => count > 1)
.map(([word]) => word)
.join(' ');
กรณีพิเศษที่ควรจัดการ
- Case Sensitivity: 'This' vs 'this' (ใช้ toLowerCase())
- Punctuation: 'word,' vs 'word' (ใช้ regex แยกคำ)
- Whitespace หลายประเภท: ใช้ `split(/\s+/)`
เวอร์ชันที่แข็งแกร่งกว่า
const keepDuplicateWordsRobust = (str) => {
// แยกคำด้วย regex (รองรับ punctuation และ whitespace หลากหลาย)
const words = str.toLowerCase().match(/\b\w+\b/g) || [];
const freq = new Map();
for (const word of words) {
freq.set(word, (freq.get(word) || 0) + 1);
}
return [...freq.entries()]
.filter(([_, count]) => count > 1)
.map(([word]) => word)
.join(' ');
};
การประยุกต์ใช้
- Text Analysis: หาคำสำคัญที่ซ้ำ
- SEO: ตรวจสอบ Keyword Stuffing
- Plagiarism Detection: หาคำซ้ำผิดปกติ
- Data Cleaning: หาข้อมูลซ้ำใน Text Fields