Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

การนับจำนวนออบเจกต์ที่เหมือนกันใน 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