ข้ามไปเนื้อหาหลัก

Object.groupBy — จัดกลุ่ม array ใน ES2024 โดยไม่ต้องเขียน reduce

Object.groupBy(array, keyFn) แทน reduce ที่ verbose — ส่งคืน object ที่ key คือค่าที่ groupBy และ value คือ array ของ items ในกลุ่มนั้น

ก่อนหน้านี้ต้องเขียน reduce เอง:

const grouped = items.reduce((acc, item) => {
  const key = item.status;
  (acc[key] ??= []).push(item);
  return acc;
}, {});

ตอนนี้มี Object.groupBy:

const grouped = Object.groupBy(items, (item) => item.status);
// { active: [...], done: [...], archived: [...] }

ใช้กับ Map ก็ได้ผ่าน Map.groupBy — เหมาะเมื่อ key ไม่ใช่ string:

const byCount = Map.groupBy(items, (item) =>
  item.count > 10 ? 'many' : 'few'
);

Support: Chrome 117+, Firefox 119+, Safari 17.4+ — ตรวจก่อน deploy ถ้ายังต้อง support เก่า ใช้ polyfill หรือเขียน reduce ไว้ก่อน