मान लीजिए, हमारे पास इस तरह की वस्तुओं की एक सरणी है -
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 } ]