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

การจัดกลุ่มอาร์เรย์แบบซับซ้อนใน JavaScript


ภาพรวม

สมมติว่าเรามีอาร์เรย์ของอ็อบเจ็กต์:

const arr = [
  {userId: "3t5bsFB4PJmA3oTnm", from: 1, to: 6},
  {userId: "3t5bsFB4PJmA3oTnm", from: 7, to: 15},
  {userId: "3t5bsFB4PJmA3oTnm", from: 172, to: 181},
  {userId: "3t5bsFB4PJmA3oTnm", from: 182, to: 190}
];

เราต้องเขียนฟังก์ชันที่จัดกลุ่มอ็อบเจ็กต์ที่ทับซ้อนกันตามคุณสมบัติ "from" และ "to" ให้เป็นอ็อบเจ็กต์เดียว

ผลลัพธ์ที่คาดหวัง

const output = [
  {userId: "3t5bsFB4PJmA3oTnm", from: 1, to: 15},
  {userId: "3t5bsFB4PJmA3oTnm", from: 172, to: 190}
];

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

const arr = [
  {userId: "3t5bsFB4PJmA3oTnm", from: 1, to: 6},
  {userId: "3t5bsFB4PJmA3oTnm", from: 7, to: 15},
  {userId: "3t5bsFB4PJmA3oTnm", from: 172, to: 181},
  {userId: "3t5bsFB4PJmA3oTnm", from: 182, to: 190}
];

const groupByDuration = (arr = []) => {
  const result = arr.reduce((acc, val) => {
    let last = acc[acc.length - 1] || {};
    if (last.userId === val.userId && last.to + 1 === val.from) {
      last.to = val.to;
    } else {
      acc.push({ userId: val.userId, from: val.from, to: val.to });
    }
    return acc;
  }, []);
  return result;
};

console.log(groupByDuration(arr));

ผลลัพธ์ในคอนโซล

[
  { userId: '3t5bsFB4PJmA3oTnm', from: 1, to: 15 },
  { userId: '3t5bsFB4PJmA3oTnm', from: 172, to: 190 }
]