Skip to content
Grok

sorting (จัดเรียง)

การเรียงลำดับข้อมูลเป็นพื้นฐานสำคัญในการจัดการข้อมูล ช่วยให้ค้นหาข้อมูลได้รวดเร็วขึ้น และเป็นพื้นฐานของอัลกอริทึมอื่นๆ

ts
// ตัวอย่างการเรียงลำดับอาเรย์
const numbers = [5, 2, 8, 1, 4];
const sortedNumbers = numbers.sort((a, b) => a - b);
console.log(sortedNumbers); // [1, 2, 4, 5, 8]

// เรียงลำดับอ็อบเจ็กต์ตามคุณสมบัติ
const users = [
  { name: "สมชาย", age: 35 },
  { name: "วิชัย", age: 28 },
  { name: "นภา", age: 42 },
];
const sortedByAge = users.sort((a, b) => a.age - b.age);

grouping (จัดกลุ่ม)

การจัดกลุ่มข้อมูลช่วยในการจัดระเบียบข้อมูลที่เกี่ยวข้องกันเข้าด้วยกัน ทำให้จัดการและวิเคราะห์ข้อมูลได้ง่ายขึ้น

ts
// จัดกลุ่มด้วย reduce
const people = [
  { name: "สมหมาย", gender: "male", age: 22 },
  { name: "สมศรี", gender: "female", age: 35 },
  { name: "สมชาย", gender: "male", age: 45 },
];

const groupedByGender = people.reduce((groups, person) => {
  const key = person.gender;
  if (!groups[key]) {
    groups[key] = [];
  }
  groups[key].push(person);
  return groups;
}, {});

// ใช้ Object.groupBy (ฟีเจอร์ใหม่ใน JavaScript)
const groupedByAgeRange = Object.groupBy(
  people,
  person => person.age < 30 ? "young" : "adult",
);

searching (ค้นหา)

อัลกอริทึมการค้นหาช่วยในการหาข้อมูลที่ต้องการจากชุดข้อมูลขนาดใหญ่ มีหลายวิธีด้วยกัน ขึ้นอยู่กับลักษณะของข้อมูล

ts
// Linear Search
function linearSearch<T>(array: T[], target: T): number {
  for (let i = 0; i < array.length; i++) {
    if (array[i] === target) return i;
  }
  return -1;
}

// Binary Search (สำหรับอาร์เรย์ที่เรียงลำดับแล้ว)
function binarySearch(sortedArray: number[], target: number): number {
  let left = 0;
  let right = sortedArray.length - 1;

  while (left <= right) {
    const mid = Math.floor((left + right) / 2);

    if (sortedArray[mid] === target) return mid;
    if (sortedArray[mid] < target) left = mid + 1;
    else right = mid - 1;
  }

  return -1;
}

filtering (กรอง)

การกรองข้อมูลช่วยคัดเลือกเฉพาะข้อมูลที่ตรงตามเงื่อนไขที่กำหนด ช่วยลดปริมาณข้อมูลที่ต้องประมวลผล

ts
// กรองข้อมูลด้วย filter
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const evenNumbers = numbers.filter(num => num % 2 === 0);

// กรองข้อมูลที่ซับซ้อนมากขึ้น
const products = [
  { name: "โทรศัพท์", price: 12000, inStock: true },
  { name: "แล็ปท็อป", price: 35000, inStock: true },
  { name: "หูฟัง", price: 2500, inStock: false },
];

const availableExpensiveProducts = products.filter(
  product => product.inStock && product.price > 10000,
);

mapping (แปลงข้อมูล)

การแปลงข้อมูลช่วยเปลี่ยนรูปแบบของข้อมูลให้อยู่ในรูปแบบที่ต้องการ โดยไม่เปลี่ยนโครงสร้างพื้นฐานของข้อมูล

ts
// แปลงข้อมูลด้วย map
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6, 8, 10]

// แปลงข้อมูลอ็อบเจ็กต์
const users = [
  { firstName: "สมชาย", lastName: "ใจดี", age: 25 },
  { firstName: "สมศรี", lastName: "รักเรียน", age: 22 },
];

const userNames = users.map(user => ({
  fullName: `${user.firstName} ${user.lastName}`,
  isAdult: user.age >= 18,
}));

reducing (ลดทอนข้อมูล)

การลดทอนข้อมูลช่วยรวบรวมข้อมูลหลายๆ ค่าให้เหลือค่าเดียว หรือเปลี่ยนโครงสร้างข้อมูลให้อยู่ในรูปแบบที่ต้องการ

ts
// หาผลรวม
const total = [1, 2, 3, 4].reduce((sum, num) => sum + num, 0);

// นับจำนวนสมาชิกตามเงื่อนไข
const users = [
  { name: "สมชาย", age: 25 },
  { name: "สมหญิง", age: 17 },
  { name: "สมหมาย", age: 30 },
];

const countAdults = users.reduce(
  (count, user) => user.age >= 18 ? count + 1 : count,
  0,
);

// รวมข้อมูลจากหลายอ็อบเจ็กต์
const items = [
  { type: "book", price: 100 },
  { type: "pen", price: 20 },
  { type: "book", price: 150 },
];

const totalByType = items.reduce((acc, item) => ({
  ...acc,
  [item.type]: (acc[item.type] || 0) + item.price,
}), {});
// ผลลัพธ์: { book: 250, pen: 20 }

chunking (แบ่งข้อมูลเป็นก้อนๆ)

การแบ่งข้อมูลเป็นส่วนย่อยๆ ช่วยในการจัดการข้อมูลขนาดใหญ่ ทำให้ประมวลผลได้ง่ายขึ้น และเหมาะสำหรับการแบ่งโหลดข้อมูล

ts
function chunkArray<T>(array: T[], size: number): T[][] {
  const chunks = [];
  for (let i = 0; i < array.length; i += size) {
    chunks.push(array.slice(i, i + size));
  }
  return chunks;
}

// ตัวอย่างการใช้งาน
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const chunks = chunkArray(numbers, 3);
// ผลลัพธ์: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

// ใช้งานกับข้อมูลจริง
const users = [
  { id: 1, name: "สมชาย" },
  { id: 2, name: "สมหญิง" },
  { id: 3, name: "สมหมาย" },
  { id: 4, name: "สมศรี" },
  { id: 5, name: "สมปอง" },
];

const userChunks = chunkArray(users, 2);
// ผลลัพธ์: [
//   [{ id: 1, name: 'สมชาย' }, { id: 2, name: 'สมหญิง' }],
//   [{ id: 3, name: 'สมหมาย' }, { id: 4, name: 'สมศรี' }],
//   [{ id: 5, name: 'สมปอง' }]
// ]

memoization (เก็บผลลัพธ์เพื่อเพิ่มประสิทธิภาพ)

เทคนิคการเก็บผลลัพธ์การคำนวณไว้ใช้งานซ้ำ ช่วยเพิ่มประสิทธิภาพการทำงานของฟังก์ชันที่เรียกบ่อยๆ ด้วยข้อมูลเดิม

ts
function memoize<T extends (...args: any[]) => any>(fn: T): T {
  const cache = new Map();
  return ((...args: any[]) => {
    const key = JSON.stringify(args);
    if (cache.has(key)) {
      console.log("ดึงจากแคช:", key);
      return cache.get(key);
    }
    const result = fn(...args);
    cache.set(key, result);
    return result;
  }) as T;
}

// ตัวอย่างการใช้งานกับฟังก์ชันคำนวณแฟกทอเรียล
const factorial = memoize((n: number): number => {
  console.log("คำนวณ factorial ของ", n);
  return n <= 1 ? 1 : n * factorial(n - 1);
});

// ครั้งแรกจะคำนวณจริง
console.log(factorial(5)); // คำนวณ 5, 4, 3, 2, 1, 0
// ครั้งถัดไปจะดึงจากแคช
console.log(factorial(5)); // ดึงจากแคช

// ตัวอย่างการใช้งานกับฟังก์ชันที่ใช้เวลาคำนวณนาน
const expensiveCalculation = memoize((a: number, b: number) => {
  console.log("กำลังคำนวณ...");
  // จำลองการคำนวณที่ใช้เวลานาน
  return a * b;
});

console.log(expensiveCalculation(10, 20)); // คำนวณจริง
console.log(expensiveCalculation(10, 20)); // ดึงจากแคช