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

การจัดกลุ่ม (Group By) JavaScript Array Object

สมมติเรามีอาร์เรย์ของอาร์เรย์ที่มีคะแนนนักเรียนในวิชาต่างๆ แบบนี้:

const arr = [
  ["English", 52],
  ["Hindi", 154],
  ["Hindi", 241],
  ["Spanish", 10],
  ["French", 65],
  ["German", 98],
  ["Russian", 10]
];

เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่รับอาร์เรย์แบบนี้เข้ามาและคืนออบเจกต์ของออบเจกต์

ออบเจกต์ผลลัพธ์ควรมีออบเจกต์สำหรับแต่ละวิชาที่ไม่ซ้ำกัน และออบเจกต์นั้นควรมีข้อมูล เช่น จำนวนครั้งที่ปรากฏ ผลรวมคะแนน และค่าเฉลี่ย

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

const arr = [
  ["English", 52],
  ["Hindi", 154],
  ["Hindi", 241],
  ["Spanish", 10],
  ["French", 65],
  ["German", 98],
  ["Russian", 10]
];
const groupSubjects = arr => {
  const grouped = arr.reduce((acc, val) => {
    const [key, total] = val;
    if(!acc.hasOwnProperty(key)){
      acc[key] = {
        'count': 0,
        'total': 0
      };
    };
    const accuKey = acc[key];
    accuKey['count']++;
    accuKey['total'] += total;
    accuKey['average'] = total / accuKey['count'];
    return acc;
  }, {});
  return grouped;
};
console.log(groupSubjects(arr));

ผลลัพธ์

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

{
  English: { count: 1, total: 52, average: 52 },
  Hindi: { count: 2, total: 395, average: 120.5 },
  Spanish: { count: 1, total: 10, average: 10 },
  French: { count: 1, total: 65, average: 65 },
  German: { count: 1, total: 98, average: 98 },
  Russian: { count: 1, total: 10, average: 10 }
}