मान लीजिए, हमारे पास ऑब्जेक्ट्स की एक सरणी है जैसे −
const arr = [ { region: "Africa", fruit: "Orange", user: "Gary" }, { region: "Africa", fruit: "Apple", user: "Steve" }, { region: "Europe", fruit: "Orange", user: "John" }, { region: "Europe", fruit: "Apple", user: "bob" }, { region: "Asia", fruit: "Orange", user: "Ian" }, { region: "Asia", fruit: "Apple", user: "Angelo" }, { region: "Africa", fruit: "Orange", user: "Gary" } ];हमें एक JavaScript फ़ंक्शन लिखना आवश्यक है जो ऐसी एक सरणी लेता है। फ़ंक्शन को ऑब्जेक्ट्स की एक नई सरणी तैयार करनी चाहिए जो ऑब्जेक्ट्स की "area" प्रॉपर्टी के आधार पर डेटा को समूहित करती है।
फ़ंक्शन को किसी विशेष क्षेत्र के लिए अद्वितीय उपयोगकर्ताओं की गिनती भी रखनी चाहिए।
इसलिए, उपरोक्त सरणी के लिए, आउटपुट इस तरह दिखना चाहिए −
const output = [ { "region": "Africa", "count": 2 }, { "region": "Europe", "count": 2 }, { "region": "Asia", "count": 2 } ];उदाहरण
इसके लिए कोड होगा −
const arr = [ { region: "Africa", fruit: "Orange", user: "Gary" }, { region: "Africa", fruit: "Apple", user: "Steve" }, { region: "Europe", fruit: "Orange", user: "John" }, { region: "Europe", fruit: "Apple", user: "bob" }, { region: "Asia", fruit: "Orange", user: "Ian" }, { region: "Asia", fruit: "Apple", user: "Angelo" }, { region: "Africa", fruit: "Orange", user: "Gary" } ]; const groupByArea = (arr = []) => { const res = []; arr.forEach(el => { let key = [el.region, el.user].join('|'); if (!this[el.region]) { this[el.region] = { region: el.region, count: 0 }; res.push(this[el.region]); }; if (!this[key]) { this[key] = true; this[el.region].count++; }; }, Object.create(null)); return res; } console.log(groupByArea(arr));आउटपुट
और कंसोल में आउटपुट होगा −
[ { region: 'Africa', count: 2 }, { region: 'Europe', count: 2 }, { region: 'Asia', count: 2 } ]