สมมติว่าเรามีอาร์เรย์ของวัตถุที่อธิบายเส้นทางของเที่ยวบินบางเที่ยวบินเช่นนี้ −
const routes = [
{
flyFrom: "CDG",
flyTo: "DUB",
return: 0,
},
{
flyFrom: "DUB",
flyTo: "SXF",
return: 0,
},
{
flyFrom: "SFX",
flyTo: "CDG",
return: 1,
}
]; เราต้องนับว่ามีผลตอบแทน − 0 กี่ครั้งและได้ผลตอบแทนกี่ครั้ง: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