สมมติว่าเรามีอาร์เรย์ของอ็อบเจ็กต์ที่มีข้อมูลเกี่ยวกับผลไม้และผักแบบนี้:
const arr = [
{food: 'apple', type: 'fruit'},
{food: 'potato', type: 'vegetable'},
{food: 'banana', type: 'fruit'},
];
เราต้องเขียนฟังก์ชัน JavaScript ที่รับอาร์เรย์ดังกล่าว ฟังก์ชันควรจัดกลุ่มอ็อบเจ็กต์ในอาร์เรย์ตามคุณสมบัติ "type" หมายความว่าอ็อบเจ็กต์ประเภท "fruit" จะถูกจัดกลุ่มร่วมกัน และประเภท "vegetable" จะถูกจัดกลุ่มแยกต่างหาก
ตัวอย่างโค้ด
โค้ดสำหรับทำสิ่งนี้คือ:
const arr = [
{food: 'apple', type: 'fruit'},
{food: 'potato', type: 'vegetable'},
{food: 'banana', type: 'fruit'},
];
const transformArray = (arr = []) => {
const res = [];
const map = {};
let i, j, curr;
for (i = 0, j = arr.length; i < j; i++) {
curr = arr[i];
if (!(curr.type in map)) {
map[curr.type] = {type: curr.type, foods: []};
res.push(map[curr.type]);
};
map[curr.type].foods.push(curr.food);
};
return res;
};
console.log(transformArray(arr));
ผลลัพธ์
ผลลัพธ์ในคอนโซลจะเป็นดังนี้:
[
{ type: 'fruit', foods: [ 'apple', 'banana' ] },
{ type: 'vegetable', foods: [ 'potato' ] }
]