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

การนับจำนวนชนิดข้อมูลในอาร์เรย์ - JavaScript

ฟังก์ชันนี้รับอาร์เรย์ที่มีข้อมูลหลายชนิด (mixed types) และคืน Map ที่นับจำนวนของแต่ละชนิดข้อมูล

ตัวอย่าง

Input: [23, 'df', undefined, null, 12, {name: 'Rajesh'}, [2,4,7], 'dfd', null, Symbol('*'), 8]

Output: Map { 'number' => 3, 'string' => 2, 'undefined' => 1, 'object' => 4, 'symbol' => 1 }

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

const arr = [23, 'df', undefined, null, 12, { name: 'Rajesh' }, [2, 4, 7], 'dfd', null, Symbol('*'), 8];

const countDataTypes = arr => {
  return arr.reduce((acc, val) => {
    const dataType = typeof val;
    if (acc.has(dataType)) {
      acc.set(dataType, acc.get(dataType) + 1);
    } else {
      acc.set(dataType, 1);
    }
    return acc;
  }, new Map());
};

console.log(countDataTypes(arr));

ข้อสังเกตเกี่ยวกับ typeof

  • typeof null === 'object' (JavaScript quirk)
  • typeof [] === 'object'
  • typeof Symbol() === 'symbol'

ผลลัพธ์

Map(5) { 'number' => 3, 'string' => 2, 'undefined' => 1, 'object' => 4, 'symbol' => 1 }