Computer >> 컴퓨터 >  >> 프로그램 작성 >> JavaScript

JavaScript에서 동일한 객체의 총 수 얻기

<시간/>

다음과 같은 일부 항공편의 경로를 설명하는 객체 배열이 있다고 가정합니다.

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