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

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


สมมติว่าเรามีอาร์เรย์ของค่าดังนี้

const arr = [ 
  { 
    value1:[1,2], 
    value2:[{type:'A'}, {type:'B'}] 
  }, 
  { 
    value1:[3,5], 
    value2:[{type:'B'}, {type:'B'}] 
  } 
];

เราต้องเขียนฟังก์ชัน JavaScript ที่รับอาร์เรย์ดังกล่าว ฟังก์ชันควรเตรียมอาร์เรย์ที่ข้อมูลถูกจัดกลุ่มตาม property "type" ของออบเจกต์

ดังนั้น สำหรับอาร์เรย์ข้างต้น ผลลัพธ์ควรเป็นดังนี้

const output = [ 
  {type:'A', value: [1,2]}, 
  {type:'B', value: [3,5]} 
];

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

โค้ดสำหรับการทำงานนี้จะเป็นดังนี้

const arr = [ 
  { 
    value1:[1,2], 
    value2:[{type:'A'}, {type:'B'}] 
  }, 
  { 
    value1:[3,5], 
    value2:[{type:'B'}, {type:'B'}] 
  } 
]; 
const groupValues = (arr = []) => { 
  const res = []; 
  arr.forEach((el, ind) => { 
    const thisObj = this; 
    el.value2.forEach(element => { 
      if (!thisObj[element.type]) { 
        thisObj[element.type] = { 
          type: element.type, 
          value: [] 
        } 
        res.push(thisObj[element.type]); 
      }; 
      if (!thisObj[ind + '|' + element.type]) { 
        thisObj[element.type].value = 
        thisObj[element.type].value.concat(el.value1); 
        thisObj[ind + '|' + element.type] = true; 
      }; 
    }); 
  }, {}) 
  return res; 
}; 
console.log(groupValues(arr));

ผลลัพธ์

ผลลัพธ์ในคอนโซลจะเป็นดังนี้

[ 
  { type: 'A', value: [ 1, 2 ] }, 
  { type: 'B', value: [ 1, 2, 3, 5 ] } 
]