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

การนับความถี่ Data Type ในอาร์เรย์ด้วย Map ใน JavaScript

ภาพรวม

บทความนี้สาธิตวิธีนับจำนวนข้อมูลแต่ละ Data Type ในอาร์เรย์ที่มีข้อมูลผสม และคืนค่าเป็น Map

ตัวอย่าง

const arr = [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 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));

ผลลัพธ์

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

ข้อสังเกตสำคัญ: typeof Quirks

ValuetypeofNote
null'object'JavaScript Bug แห่งดั้งเดิม
[]'object'Array เป็น Object
{}'object'Plain Object
function() {}'function'Function เป็น Type แยก
Symbol()'symbol'ES6+
123n'bigint'ES2020+

เวอร์ชันที่แยก Array และ Null

const countDataTypesDetailed = (arr) => {
  return arr.reduce((acc, val) => {
    let type = typeof val;
    if (val === null) type = 'null';
    else if (Array.isArray(val)) type = 'array';
    
    acc.set(type, (acc.get(type) || 0) + 1);
    return acc;
  }, new Map());
};

การประยุกต์ใช้

  • Data Validation / Schema Inference
  • Debugging: Inspect Mixed Arrays
  • Serialization: เลือก Serializer ต่อ Type
  • TypeScript: Runtime Type Analysis

Output เป็น Object แทน Map

const countDataTypesObject = (arr) => 
  arr.reduce((acc, val) => {
    const type = Array.isArray(val) ? 'array' : val === null ? 'null' : typeof val;
    acc[type] = (acc[type] || 0) + 1;
    return acc;
  }, {});