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

Category: reference

JavaScript Array Methods ที่ใช้บ่อยใน Frontend

รวม array methods สำคัญใน JavaScript/TypeScript ที่ใช้จริงในการ transform, filter, และ reduce data ก่อน render ใน Astro/React

· อ่านประมาณ 3 นาที

สารบัญ

Methods พื้นฐาน

map() — แปลงทุก element

const projects = [
  { id: 'a', title: 'Project A', date: '2025-01-01' },
  { id: 'b', title: 'Project B', date: '2025-06-01' },
];

// เพิ่ม property ใหม่ให้ทุก element
const withSlug = projects.map((p) => ({
  ...p,
  href: `/projects/${p.id}`,
}));

filter() — กรอง element ที่ตรงเงื่อนไข

// กรองเฉพาะ projects ที่ active
const active = projects.filter((p) => p.status === 'active');

// กรองค่าที่ไม่ใช่ null/undefined
const defined = items.filter((x): x is NonNullable<typeof x> => x != null);

reduce() — รวบรวม elements เป็นค่าเดียว

// นับ projects ตาม status
const countByStatus = projects.reduce<Record<string, number>>((acc, p) => {
  acc[p.status] = (acc[p.status] ?? 0) + 1;
  return acc;
}, {});
// { active: 3, completed: 5, archived: 1 }

// รวม tags ทั้งหมด (flatten + unique)
const allTags = projects.reduce<string[]>((acc, p) => {
  return [...acc, ...(p.tags ?? [])];
}, []);

find() / findIndex()

const current = projects.find((p) => p.id === slug);
const index = projects.findIndex((p) => p.id === slug);
const prev = index > 0 ? projects[index - 1] : null;

some() / every()

const hasActive = projects.some((p) => p.status === 'active');
const allCompleted = projects.every((p) => p.status === 'completed');

includes()

const VALID_STATUSES = ['active', 'completed', 'archived'] as const;
if (VALID_STATUSES.includes(status)) { /* ... */ }

Methods ที่มักลืม

flat() และ flatMap()

// กรณีที่ map แล้วได้ array ซ้อนกัน
const allTags = projects
  .map((p) => p.tags ?? [])
  .flat();

// แบบสั้นกว่า
const allTags = projects.flatMap((p) => p.tags ?? []);

at() — index แบบ negative

const arr = [1, 2, 3, 4, 5];
arr.at(-1)   // 5 (element สุดท้าย)
arr.at(-2)   // 4

Array.from()

// จาก Set → array (dedup)
const uniqueTags = Array.from(new Set(allTags));

// สร้าง array จาก length
const slots = Array.from({ length: 5 }, (_, i) => i + 1);
// [1, 2, 3, 4, 5]

Object.entries() / Object.fromEntries()

const tagCount = { astro: 5, typescript: 8, css: 3 };

// sort by count
const sorted = Object.entries(tagCount)
  .sort(([, a], [, b]) => b - a)
  .map(([tag, count]) => ({ tag, count }));

// filter + convert back to object
const popular = Object.fromEntries(
  Object.entries(tagCount).filter(([, count]) => count >= 5)
);

Patterns ที่ใช้บ่อยใน Astro

Sort ตาม date (descending)

const sorted = posts.sort(
  (a, b) => new Date(b.data.date).getTime() - new Date(a.data.date).getTime()
);

Group by tag

const byTag = resources.reduce<Record<string, typeof resources>>((acc, r) => {
  for (const tag of r.data.tags ?? []) {
    acc[tag] = [...(acc[tag] ?? []), r];
  }
  return acc;
}, {});

เลือก prev / next item

const items = allPosts.sort(/* by date */);
const idx = items.findIndex((p) => p.id === current.id);
const prev = items[idx + 1] ?? null;
const next = items[idx - 1] ?? null;

Tips TypeScript

// Type predicate สำหรับ filter null
function isDefined<T>(x: T | null | undefined): x is T {
  return x !== null && x !== undefined;
}

const defined = items.filter(isDefined);
// readonly array ป้องกัน mutation
const STATUS = ['active', 'completed', 'archived'] as const;
type Status = (typeof STATUS)[number];