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

จัดกลุ่มอาร์เรย์และนับรายการสร้างอาร์เรย์ใหม่จากกลุ่มใน JavaScript


สมมติว่าเรามีอาร์เรย์ของออบเจกต์ดังนี้

const arr = [ 
  { region: "Africa", fruit: "Orange", user: "Gary" }, 
  { region: "Africa", fruit: "Apple", user: "Steve" }, 
  { region: "Europe", fruit: "Orange", user: "John" }, 
  { region: "Europe", fruit: "Apple", user: "bob" }, 
  { region: "Asia", fruit: "Orange", user: "Ian" }, 
  { region: "Asia", fruit: "Apple", user: "Angelo" }, 
  { region: "Africa", fruit: "Orange", user: "Gary" } 
];

เราต้องเขียนฟังก์ชัน JavaScript ที่รับอาร์เรย์ดังกล่าว ฟังก์ชันควรเตรียมอาร์เรย์ใหม่ของออบเจกต์ที่จัดกลุ่มข้อมูลตาม property "area" ของออบเจกต์

ฟังก์ชันควรนับจำนวนผู้ใช้ที่ไม่ซ้ำกันสำหรับพื้นที่เฉพาะด้วย

ดังนั้น สำหรับอาร์เรย์ข้างต้น ผลลัพธ์ควรเป็นดังนี้

const output = [ 
  { 
    "region": "Africa", 
    "count": 2 
  }, 
  { 
    "region": "Europe", 
    "count": 2 
  }, 
  { 
    "region": "Asia", 
    "count": 2 
  } 
];

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

โค้ดสำหรับการทำงานนี้จะเป็นดังนี้

const arr = [ 
  { region: "Africa", fruit: "Orange", user: "Gary" }, 
  { region: "Africa", fruit: "Apple", user: "Steve" }, 
  { region: "Europe", fruit: "Orange", user: "John" }, 
  { region: "Europe", fruit: "Apple", user: "bob" }, 
  { region: "Asia", fruit: "Orange", user: "Ian" }, 
  { region: "Asia", fruit: "Apple", user: "Angelo" }, 
  { region: "Africa", fruit: "Orange", user: "Gary" } 
]; 
const groupByArea = (arr = []) => { 
  const res = []; 
  arr.forEach(el => { 
    let key = [el.region, el.user].join('|'); 
    if (!this[el.region]) { 
      this[el.region] = { region: el.region, count: 0 }; 
      res.push(this[el.region]); 
    }; 
    if (!this[key]) { 
      this[key] = true; 
      this[el.region].count++; 
    }; 
  }, Object.create(null)); 
  return res; 
} 
console.log(groupByArea(arr));

ผลลัพธ์

ผลลัพธ์ในคอนโซลจะเป็นดังนี้

[ 
  { region: 'Africa', count: 2 }, 
  { region: 'Europe', count: 2 }, 
  { region: 'Asia', count: 2 } 
]