สมมติว่าเรามีอาร์เรย์ของค่าเช่นนี้ -
const arr = [
{
value1:[1,2],
value2:[{type:'A'}, {type:'B'}]
},
{
value1:[3,5],
value2:[{type:'B'}, {type:'B'}]
}
]; เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่รับอาร์เรย์ดังกล่าว ฟังก์ชันของเราควรเตรียมอาร์เรย์ที่ข้อมูลถูกจัดกลุ่มตามคุณสมบัติ "ประเภท" ของออบเจกต์
ดังนั้น สำหรับอาร์เรย์ข้างต้น ผลลัพธ์ควรมีลักษณะดังนี้ −
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 ] }
]