获取 JavaScript 中相同对象总数
假设我们有一个描述某些航班路线的对象数组,如下所示 −
const routes = [
{
flyFrom: "CDG",
flyTo: "DUB",
return: 0,
},
{
flyFrom: "DUB",
flyTo: "SXF",
return: 0,
},
{
flyFrom: "SFX",
flyTo: "CDG",
return: 1,
}
];我们需要统计 return − 0 的次数和 return: 1 的次数。
最终输出应如下所示 −
for the cases where return: 0 appears 2 times --- 1 Stop for the cases where return: 1 appears 1 time --- 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP