मान लीजिए, हमारे पास ऑब्जेक्ट की एक सरणी है जिसमें कुछ उपयोगकर्ताओं के बारे में डेटा है जैसे -
const arr = [
{
"name":"aaa",
"id":"2100",
"designation":"developer"
},
{
"name":"bbb",
"id":"8888",
"designation":"team lead"
},
{
"name":"ccc",
"id":"6745",
"designation":"manager"
},
{
"name":"aaa",
"id":"9899",
"designation":"sw"
}
];
हमें एक JavaScript फ़ंक्शन लिखना है जो ऐसी एक सरणी लेता है। फिर हमारा फ़ंक्शन एक नया ऑब्जेक्ट लौटाना चाहिए जिसमें उन सभी name प्रॉपर्टी मान शामिल हों जो उस विशिष्ट name प्रॉपर्टी वाले ऑब्जेक्ट की गिनती से मैप किए गए हों।
इसलिए, उपरोक्त सरणी के लिए, आउटपुट इस तरह दिखना चाहिए -
const output = {
"aaa": 2,
"bbb": 1,
"ccc": 1
};
उदाहरण
इसके लिए कोड होगा -
const arr = [
{
"name":"aaa",
"id":"2100",
"designation":"developer"
},
{
"name":"bbb",
"id":"8888",
"designation":"team lead"
},
{
"name":"ccc",
"id":"6745",
"designation":"manager"
},
{
"name":"aaa",
"id":"9899",
"designation":"sw"
}
];
const countNames = (arr = []) => {
const res = {};
for(let i = 0; i < arr.length; i++){
const { name } = arr[i];
if(res.hasOwnProperty(name)){
res[name]++;
}
else{
res[name] = 1;
};
};
return res;
};
console.log(countNames(arr));
आउटपुट
कंसोल में आउटपुट होगा -
{ aaa: 2, bbb: 1, ccc: 1 }