ধরুন, আমাদের কাছে এই ধরনের বস্তুর একটি অ্যারে আছে −
const arr = [
{
"customer": "Customer 1",
"project": "1"
},
{
"customer": "Customer 2",
"project": "2"
},
{
"customer": "Customer 2",
"project": "3"
}
] আমাদের একটি জাভাস্ক্রিপ্ট ফাংশন লিখতে হবে যা এই ধরনের একটি অ্যারে নেয় এবং একটি নতুন অ্যারে দেয় (ফেরত দেয়)৷
নতুন অ্যারেতে, একই মান সহ সমস্ত গ্রাহক কীগুলিকে একত্রিত করা উচিত এবং আউটপুটটি এইরকম দেখতে হবে −
const output = [
{
"Customer 1": {
"projects": "1"
}
},
{
"Customer 2": {
"projects": [
"2",
"3"
]
}
}
] উদাহরণ
আসুন কোড লিখি −
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' ] }
]