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

วนลูปอาร์เรย์อ็อบเจ็กต์สร้างอันใหม่จัดกลุ่ม customer - JavaScript

อาร์เรย์: [{customer: "Customer 1", project: "1"}, {customer: "Customer 2", project: "2"}, {customer: "Customer 2", project: "3"}]

จัดกลุ่ม customer เดียวกัน รวม project เป็นอาร์เรย์

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

const arr = [
  { "customer": "Customer 1", "project": "1" },
  { "customer": "Customer 2", "project": "2" },
  { "customer": "Customer 2", "project": "3" }
];

const groupCustomer = data => {
  const res = [];
  data.forEach(el => {
    let customer = res.filter(custom => {
      return el.customer === custom.customer;
    })[0];
    if (customer) {
      customer.projects.push(el.project);
    } else {
      res.push({ customer: el.customer, projects: [el.project] });
    }
  });
  return res;
};

console.log(groupCustomer(arr));

ผลลัพธ์

[ { customer: 'Customer 1', projects: [ '1' ] }, { customer: 'Customer 2', projects: [ '2', '3' ] } ]

คำอธิบาย: วนลูปข้อมูล หาใน res ว่ามี customer นี้แล้วไหม (filter) ถ้ามี push project ถ้าไม่มี push object ใหม่

ประสิทธิภาพ: ใช้ Map หรือ object เป็น lookup จะเร็วกว่า O(n) แทน O(n²)