ปัญหา
เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่ใช้อาร์เรย์ประเภทข้อมูลแบบผสม ฟังก์ชันของเราควรส่งคืนอ็อบเจ็กต์ที่มีชื่อประเภทข้อมูลเป็นคีย์ และค่าของออบเจ็กต์ดังกล่าวเป็นอาร์เรย์ขององค์ประกอบประเภทข้อมูลเฉพาะที่มีอยู่ในอาร์เรย์
ตัวอย่าง
ต่อไปนี้เป็นรหัส -
const arr = [1, 'a', [], '4', 5, 34, true, undefined, null];
const groupDataTypes = (arr = []) => {
const res = {};
for(let i = 0; i < arr.length; i++){
const el = arr[i];
const type = typeof el;
if(res.hasOwnProperty(type)){
res[type].push(el);
}else{
res[type] = [el];
};
};
return res;
};
console.log(groupDataTypes(arr)); ผลลัพธ์
ต่อไปนี้เป็นเอาต์พุตคอนโซล -
{
number: [ 1, 5, 34 ],
string: [ 'a', '4' ],
object: [ [], null ],
boolean: [ true ],
undefined: [ undefined ]
}