मान लीजिए, हमारे पास एक JavaScript सरणी है जैसे -
const data = [ { "dataId": "1", "tableName": "table1", "column": "firstHeader", "rows": [ "a","b","c" ] }, { "dataId": "2", "tableName": "table1", "column": "secondHeader", "rows": [ "d","e","f", ] }, { "dataId": "3", "tableName": "table2", "column": "aNewFirstHeader", "rows": [ 1,2,3 ] } ];हमें एक JavaScript फ़ंक्शन लिखना है जो ऐसी एक सरणी लेता है। फ़ंक्शन को मूल सरणी के आधार पर ऑब्जेक्ट्स की एक नई ग्रुप की गई सरणी बनानी चाहिए।
ग्रुप की गई सरणी में अलग, अद्वितीय "tableName" ऑब्जेक्ट्स के डेटा को उनके अपने ऑब्जेक्ट्स में होना चाहिए।
इसलिए अंततः, आउटपुट इस तरह दिखना चाहिए -
const output = [ { "tableName": "table1", "column": ["firstHeader", "secondHeader"], "rows": [["a","b","c"], ["d","e","f"]] }, { "tableName": "table2", "column": ["aNewFirstHeader"], "rows": [[1,2,3]] } ];उदाहरण
const arr = [ { "dataId": "1", "tableName": "table1", "column": "firstHeader", "rows": [ "val","b","c" ] }, { "dataId": "2", "tableName": "table1", "column": "secondHeader", "rows": [ "d","e","f", ] }, { "dataId": "3", "tableName": "table2", "column": "aNewFirstHeader", "rows": [ 1,2,3 ] } ]; const groupArray = (arr = []) => { const res = arr.reduce((obj => (acc, val) => { let item = obj.get(val.tableName); if (!item) { item = { tableName: val.tableName, column: [], rows: [] } obj.set(val.tableName, item); acc.push(item); }; item.column.push(val.column); item.rows.push(val.rows); return acc; })(new Map), []); return res; }; console.log(JSON.stringify(groupArray(arr), undefined, 4));आउटपुट
कंसोल में आउटपुट होगा -
[ { "tableName": "table1", "column": [ "firstHeader", "secondHeader" ], "rows": [ [ "val", "b", "c" ], [ "d", "e", "f" ] ] }, { "tableName": "table2", "column": [ "aNewFirstHeader" ], "rows": [ [ 1, 2, 3 ] ] } ]