สร้างออบเจ็กต์ที่ key คือตัวอักษร value คืออาร์เรย์ของตำแหน่ง (index) ที่ตัวอักษรนั้นปรากฏ
ตัวอย่าง
// Input: 'cannot'
// Output: { c: [0], a: [1], n: [2, 3], o: [4], t: [5] }
ตัวอย่างโค้ด
const str = 'cannot';
const mapString = str => {
const map = {};
for (let i = 0; i < str.length; i++) {
if (map.hasOwnProperty(str[i])) {
map[str[i]] = map[str[i]].concat(i);
} else {
map[str[i]] = [i];
}
}
return map;
};
console.log(mapString(str));
วิธีทันสมัยกว่า
const mapString = str =>
[...str].reduce((acc, ch, i) => {
(acc[ch] = acc[ch] || []).push(i);
return acc;
}, {});
ผลลัพธ์
{ c: [ 0 ], a: [ 1 ], n: [ 2, 3 ], o: [ 4 ], t: [ 5 ] }
ประยุกต์ใช้: การค้นหาตำแหน่งตัวอักษร การวิเคราะห์รูปแบบสตริง Search indexing