Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

การแยกข้อมูลในอาร์เรย์ตามประเภทข้อมูลใน JavaScript


ปัญหา

เราต้องเขียนฟังก์ชัน JavaScript ที่รับอาร์เรย์ที่มีข้อมูลหลายประเภท (mixed data types) ฟังก์ชันควรคืนค่าวัตถุ (object) ที่มีชื่อประเภทข้อมูลเป็นคีย์ (key) และค่าเป็นอาร์เรย์ของสมาชิกที่เป็นประเภทข้อมูลนั้นๆ

ตัวอย่าง

โค้ดตัวอย่างดังนี้:

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 ]
}