ধরুন, আমাদের কাছে এই ধরনের বস্তুর একটি অ্যারে আছে −
const arr = [ { Phase: "Phase 1", Step: "Step 1", Task: "Task 1", Value: "5" }, { Phase: "Phase 1", Step: "Step 1", Task: "Task 2", Value: "10" }, { Phase: "Phase 1", Step: "Step 2", Task: "Task 1", Value: "15" }, { Phase: "Phase 1", Step: "Step 2", Task: "Task 2", Value: "20" }, { Phase: "Phase 2", Step: "Step 1", Task: "Task 1", Value: "25" }, { Phase: "Phase 2", Step: "Step 1", Task: "Task 2", Value: "30" }, { Phase: "Phase 2", Step: "Step 2", Task: "Task 1", Value: "35" }, { Phase: "Phase 2", Step: "Step 2", Task: "Task 2", Value: "40" } ];
আমাদের একটি জাভাস্ক্রিপ্ট ফাংশন লিখতে হবে যা প্রথম আর্গুমেন্টের মতো একটি অ্যারে নেয়৷
আমাদের উদ্দেশ্য হল প্রদত্ত অ্যারেকে একাধিক বা একটি একক সম্পত্তির (দ্বিতীয়, তৃতীয় আর্গুমেন্ট দ্বারা নির্দেশিত) উপর ভিত্তি করে গোষ্ঠীবদ্ধ করতে সক্ষম হওয়া।
তাই, যদি আমরা গ্রুপ অনুসারে ফেজ করি, তাহলে আমাদের −
পাওয়া উচিতconst output = [ { Phase: "Phase 1", Value: 50 }, { Phase: "Phase 2", Value: 130 } ];
এবং যদি আমরা গ্রুপি ফেজ/স্টেপ করি, তাহলে আমাদের −
গ্রহণ করা উচিতconst output = [ { Phase: "Phase 1", Step: "Step 1", Value: 15 }, { Phase: "Phase 1", Step: "Step 2", Value: 35 }, { Phase: "Phase 2", Step: "Step 1", Value: 55 }, { Phase: "Phase 2", Step: "Step 2", Value: 75 } ];
উদাহরণ
এর জন্য কোড হবে −
const arr = [ { Phase: "Phase 1", Step: "Step 1", Task: "Task 1", Value: "5" }, { Phase: "Phase 1", Step: "Step 1", Task: "Task 2", Value: "10" }, { Phase: "Phase 1", Step: "Step 2", Task: "Task 1", Value: "15" }, { Phase: "Phase 1", Step: "Step 2", Task: "Task 2", Value: "20" }, { Phase: "Phase 2", Step: "Step 1", Task: "Task 1", Value: "25" }, { Phase: "Phase 2", Step: "Step 1", Task: "Task 2", Value: "30" }, { Phase: "Phase 2", Step: "Step 2", Task: "Task 1", Value: "35" }, { Phase: "Phase 2", Step: "Step 2", Task: "Task 2", Value: "40" } ]; const groupBy = (array, groups, valueKey) => { const map = new Map; groups = [].concat(groups); return array.reduce((acc, val) => { groups.reduce((accu, value, ind, { length }) => { let child; if (accu.has(val[value])) { return accu.get(val[value]); }; if (ind + 1 === length) { child = Object .assign(...groups.map(value => ({ [value]: val[value] })), { [valueKey]: 0 }); acc.push(child); } else { child = new Map; }; accu.set(val[value], child); return child; }, map)[valueKey] += +val[valueKey]; return acc; }, []); }; console.log(groupBy(arr, 'Phase', 'Value')); console.log(groupBy(arr, ['Phase', 'Step'], 'Value'));
আউটপুট
এবং কনসোলে আউটপুট হবে −
[ { Phase: 'Phase 1', Value: 50 }, { Phase: 'Phase 2', Value: 130 } ] [ { Phase: 'Phase 1', Step: 'Step 1', Value: 15 }, { Phase: 'Phase 1', Step: 'Step 2', Value: 35 }, { Phase: 'Phase 2', Step: 'Step 1', Value: 55 }, { Phase: 'Phase 2', Step: 'Step 2', Value: 75 } ]