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

배열에서 반복되는 이름의 발생 횟수를 계산하는 방법 - JavaScript?

<시간/>

다음이 우리의 배열이라고 가정해 봅시다 -

var details = [
   {
      studentName: "John",
      studentAge: 23
   },
   {
      studentName: "David",
      studentAge: 24
   },
   {
      studentName: "John",
      studentAge: 21
   },
   {
      studentName: "John",
      studentAge: 25
   },
   {
      studentName: "Bob",
      studentAge: 22
   },
   {
      studentName: "David",
      studentAge: 20
   }
]

반복되는 이름의 발생 횟수를 계산해야 합니다. 즉, 출력은 다음과 같아야 합니다.

John: 3
David: 2
Bob: 1

이를 위해 reduce() 개념을 사용할 수 있습니다.

예시

다음은 코드입니다 -

var details = [
   {
      studentName: "John",
      studentAge: 23
   },
   {
      studentName: "David",
      studentAge: 24
   },
   {
      studentName: "John",
      studentAge: 21
   },
   {
      studentName: "John",
      studentAge: 25
   },
   {
      studentName: "Bob",
      studentAge: 22
   },
   {
      studentName: "David",
      studentAge: 20
   }
]
var output = Object.values(details.reduce((obj, { studentName }) => {
   if (obj[studentName] === undefined)
      obj[studentName] = { studentName: studentName, occurrences: 1 };
   else
      obj[studentName].occurrences++;
   return obj;
}, {}));
console.log(output);

위의 프로그램을 실행하려면 다음 명령을 사용해야 합니다 -

node fileName.js.

여기에서 내 파일 이름은 demo282.js입니다. 이것은 콘솔에 다음과 같은 출력을 생성합니다 -

PS C:\Users\Amit\javascript-code> node demo282.js
[
   { studentName: 'John', occurrences: 3 },
   { studentName: 'David', occurrences: 2 },
   { studentName: 'Bob', occurrences: 1 }
]