สมมติเรามีสตริงยาวที่แทนตัวเลข เช่น:
const str = '11222233344444445666';
เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่รับสตริงแบบนี้เข้ามา ฟังก์ชันควรคืนออบเจกต์ที่กำหนด property "id" ให้แต่ละตัวเลขที่ไม่ซ้ำกันในสตริง และ property "count" (หรือ displayed) ที่เก็บจำนวนครั้งที่ตัวเลขปรากฏ
ดังนั้น สำหรับสตริงข้างต้น ผลลัพธ์ควรเป็น:
const output = {
'1': { id: '1', displayed: 2 },
'2': { id: '2', displayed: 4 },
'3': { id: '3', displayed: 3 },
'4': { id: '4', displayed: 7 },
'5': { id: '5', displayed: 1 },
'6': { id: '6', displayed: 3 }
};
ตัวอย่างโค้ด
const str = '11222233344444445666';
const countNumberFrequency = str => {
const map = {};
for(let i = 0; i < str.length; i++){
const el = str[i];
if(map.hasOwnProperty(el)){
map[el]['displayed']++;
}else{
map[el] = {
id: el,
displayed: 1
};
};
};
return map;
};
console.log(countNumberFrequency(str));
ผลลัพธ์
ผลลัพธ์ที่แสดงในคอนโซลจะเป็นดังนี้:
{
'1': { id: '1', displayed: 2 },
'2': { id: '2', displayed: 4 },
'3': { id: '3', displayed: 3 },
'4': { id: '4', displayed: 7 },
'5': { id: '5', displayed: 1 },
'6': { id: '6', displayed: 3 }
}