मान लीजिए, हमारे पास मानों की एक सरणी है जैसे −
const arr = [ { value1:[1,2], value2:[{type:'A'}, {type:'B'}] }, { value1:[3,5], value2:[{type:'B'}, {type:'B'}] } ];हमें एक JavaScript फ़ंक्शन लिखना आवश्यक है जो ऐसी एक सरणी लेता है। हमारा फ़ंक्शन तब एक सरणी तैयार करनी चाहिए जहां डेटा ऑब्जेक्ट्स की "type" प्रॉपर्टी के अनुसार समूहित हो।
इसलिए, उपरोक्त सरणी के लिए, आउटपुट इस तरह दिखना चाहिए −
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 ] } ]