मान लीजिए, हमारे पास ऑब्जेक्ट की एक सरणी है जो कुछ उड़ानों के मार्गों का वर्णन करती है जैसे -
const routes = [
{
flyFrom: "CDG",
flyTo: "DUB",
return: 0,
},
{
flyFrom: "DUB",
flyTo: "SXF",
return: 0,
},
{
flyFrom: "SFX",
flyTo: "CDG",
return: 1,
}
];
हमें गिनना होगा कि कितनी बार return - 0 है और कितनी बार return: 1 है।
अंतिम आउटपुट इस तरह दिखना चाहिए -
उन मामलों के लिए जहां return: 0 दो बार आता है --- 1 Stop उन मामलों के लिए जहां return: 1 एक बार आता है --- Non-stop
उदाहरण
इसके लिए कोड होगा -
const routes = [
{
flyFrom: "CDG",
flyTo: "DUB",
return: 0,
},
{
flyFrom: "DUB",
flyTo: "SXF",
return: 0,
},
{
flyFrom: "SFX",
flyTo: "CDG",
return: 1,
}
];
const displaySimilar = arr => {
const count = {};
arr.forEach(el => {
count[el.return] = (count[el.return] || 0) + 1;
});
Object.keys(count).forEach(key => {
for(let i = 0; i < count[key]; i++){
if(key === '0'){
console.log('1 Stop');
}
else if(key === '1'){
console.log('Non-stop');
};
}
})
};
displaySimilar(routes);
आउटपुट
कंसोल में आउटपुट होगा -
1 Stop 1 Stop Non-stop