การจัดกลุ่ม (Grouping) อาร์เรย์ของอ็อบเจกต์ตามคีย์ (เช่น id, age, category) ทำได้ง่ายด้วย Array.prototype.reduce() หรือใน ES2024 ใช้ Object.groupBy() (Stage 3 proposal, รองรับในเบราว์เซอร์ใหม่ๆ)
ตัวอย่างโค้ด (Reduce - รองรับทุกเบราว์เซอร์)
<!DOCTYPE html>
<html lang="th">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>จัดกลุ่มอาร์เรย์ตาม ID</title>
<style>
body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
.result { font-size: 18px; font-weight: 500; color: rebeccapurple; white-space: pre-wrap; }
</style>
</head>
<body>
<h1>จัดกลุ่มอาร์เรย์ของอ็อบเจกต์ตาม ID ใน JavaScript</h1>
<div class="result">[
{ name: 'Rohan', age: 18 },
{ name: 'Mohan', age: 20 },
{ name: 'Shawn', age: 18 },
{ name: 'Michael', age: 18 },
{ name: 'David', age: 20 }
]</div>
<button class="Btn">คลิกที่นี่</button>
<h3>กดปุ่มเพื่อจัดกลุ่มตามอายุ (ดูผลใน Console)</h3>
<script>
const resEle = document.querySelector(".result");
const btnEle = document.querySelector(".Btn");
const people = [
{ name: "Rohan", age: 18 },
{ name: "Mohan", age: 20 },
{ name: "Shawn", age: 18 },
{ name: "Michael", age: 18 },
{ name: "David", age: 20 },
];
// ฟังก์ชันจัดกลุ่มแบบทั่วไป
const groupBy = (array, key) => {
return array.reduce((result, obj) => {
const k = obj[key];
(result[k] = result[k] || []).push(obj);
return result;
}, {});
};
const grouped = groupBy(people, "age");
btnEle.addEventListener("click", () => {
console.log("จัดกลุ่มตามอายุ:", grouped);
resEle.textContent = JSON.stringify(grouped, null, 2);
});
</script>
</body>
</html>
ผลลัพธ์

เมื่อกดปุ่ม "คลิกที่นี่" (ดูใน Console):

วิธีใหม่: Object.groupBy() (ES2024 / Stage 3)
// รองรับใน Chrome 117+, Firefox 119+, Safari 17.4+
const grouped = Object.groupBy(people, person => person.age);
// ผลลัพธ์: { 18: [...], 20: [...] }
// Object.keyBy() — คืนค่าเดียว (ไม่ใช่ array) หากคีย์ไม่ซ้ำ
const byId = Object.keyBy(people, p => p.id);
ใช้ Map แทน Object (แนะนำสำหรับข้อมูลเยอะ)
const groupByMap = (array, key) => {
return array.reduce((map, obj) => {
const k = obj[key];
if (!map.has(k)) map.set(k, []);
map.get(k).push(obj);
return map;
}, new Map());
};
// Map รองรับคีย์ทุกชนิด (ไม่แค่สตริง) และมี size, forEach, entries
ใช้ Lodash (ถ้ามี library อยู่แล้ว)
import _ from 'lodash';
const grouped = _.groupBy(people, 'age');
// หรือ
const grouped = _.groupBy(people, p => p.age);
ประสิทธิภาพ
reduce: O(n) — เร็วที่สุดสำหรับ vanilla JSObject.groupBy: Native optimized, O(n)- Map: O(n) เหมือนกัน แต่จัดการหน่วยความจำดีกว่า Object เมื่อคีย์เยอะ