ধরুন, আমাদের কাছে এই −
এর মত মানের একটি অ্যারে আছেconst arr = [
{
value1:[1,2],
value2:[{type:'A'}, {type:'B'}]
},
{
value1:[3,5],
value2:[{type:'B'}, {type:'B'}]
}
]; আমাদের একটি জাভাস্ক্রিপ্ট ফাংশন লিখতে হবে যা এমন একটি অ্যারেতে নেয়। তারপরে আমাদের ফাংশনের একটি অ্যারে প্রস্তুত করা উচিত যেখানে ডেটা বস্তুর "টাইপ" বৈশিষ্ট্য অনুসারে গোষ্ঠীবদ্ধ করা হয়৷
অতএব, উপরের অ্যারের জন্য, আউটপুটটি −
এর মত হওয়া উচিত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 ] }
]