Giả sử, chúng ta có một mảng các đối tượng mô tả lộ trình của một số chuyến bay như thế này -
const routes = [
{
flyFrom: "CDG",
flyTo: "DUB",
return: 0,
},
{
flyFrom: "DUB",
flyTo: "SXF",
return: 0,
},
{
flyFrom: "SFX",
flyTo: "CDG",
return: 1,
}
]; Chúng ta cần đếm xem có bao nhiêu lần trả về - 0 và bao nhiêu lần trả về:1.
Đầu ra cuối cùng sẽ giống như -
for the cases where return: 0 appears 2 times --- 1 Stop for the cases where return: 1 appears 1 time --- Non-stop
Ví dụ
Mã cho điều này sẽ là -
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); Đầu ra
Và đầu ra trong bảng điều khiển sẽ là -
1 Stop 1 Stop Non-stop