Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
Get the total number of same objects in JavaScript
Suppose, we have an array of objects describing the routes of some flights like this −
const routes = [
{
flyFrom: "CDG",
flyTo: "DUB",
return: 0,
},
{
flyFrom: "DUB",
flyTo: "SXF",
return: 0,
},
{
flyFrom: "SFX",
flyTo: "CDG",
return: 1,
}
];
We need to count how many times there is return − 0 and how many times there is the return: 1.
The end output should look like −
for the cases where return: 0 appears 2 times --- 1 Stop for the cases where return: 1 appears 1 time --- Non-stop
Example
The code for this will be −
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);
Output
And the output in the console will be −
1 Stop 1 Stop Non-stop
Advertisements
