獲取 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