JavaScript-배열 원소별 개수 세기

hannah·2023년 9월 22일
0

JavaScript

목록 보기
89/121

- JavaScript 배열 값 개수 세기 / JavaScript 배열 원소별 개수 세기

const arr = ['b', 'x', 'b', 'o', 'b', 'o', 'b'];
const occurrences = {};
for (const v of arr) {
  occurrences[v] = occurrences[v] ? occurrences[v] + 1 : 1;
}
console.log(occurrences); // {b: 4, x: 1, o: 2}

혹은

const arr = ['b', 'x', 'b', 'o', 'b', 'o', 'b'];
const occurrences = arr.reduce((a, i) => {return a[i]=(a[i]||0)+1, a},{});
console.log(occurrences); // {b: 4, x: 1, o: 2}

위와 같이 for문이나 reduce를 사용해서 원소별 빈도수를 체크할 수 있다.

0개의 댓글