สมมติว่าเรามีสตริงยาวที่แสดงตัวเลขเช่นนี้ −
const str = '11222233344444445666';
เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่รับสตริงดังกล่าว ฟังก์ชันของเราควรจะส่งคืนอ็อบเจ็กต์ที่ควรกำหนดคุณสมบัติ "id" ที่ไม่ซ้ำกันให้กับแต่ละหมายเลขที่ไม่ซ้ำในสตริงและอีกหนึ่งคุณสมบัติ "count" ที่เก็บการนับจำนวนครั้งที่ตัวเลขปรากฏในสตริง
ดังนั้น สำหรับสตริงข้างต้น ผลลัพธ์ควรมีลักษณะดังนี้ −
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 }
}