Front End/Javascript

배열의 각 항목별 개수 세기

YJ_SW 2023. 1. 13. 05:39
728x90

배열의 항목별 개수 세기

['a', 'b', 'c', 'b', 'd', 'a', 'c', 'c']

이와 같은 배열이 있을 때 각 항목별 개수를 세어 아래와 같은 결과를 얻고자 한다.

[ { 'a': 2 },
  { 'b': 2 },
  { 'c': 3 },
  { 'd': 1 } ]

방법

 const arr = ['a', 'b', 'c', 'b', 'd', 'a', 'c', 'c']
 let result = {}
 arr.forEach((x) => { 
 	result[x] = (result[x] || 0) + 1; 
 });
 // result {a: 2, b: 2, c: 3, d: 1}
 
 let resultArr = []
 resultArr = Object.keys(result).map((key)=>{return {[key]:result[key]}})
 // resultArr [{a: 2},{b: 2},{c: 3},{d: 1}]

result 결과는  {a: 2, b: 2, c: 3, d: 1} 이를 Object 배열로 변환하기 위해 Object.key 를 사용했다.

 

Object 생성 시 변수에 저장된 값을 key 로 사용하려면 변수명을 [ ] 로 감싸주어 사용해야 한다.

const key = "a"
const value = 1

console.log({key:value})
// {key: 1}

console.log({[key]:value})
// {a: 1}

 

 

 

https://stackoverflow.com/questions/5667888/counting-the-occurrences-frequency-of-array-elements

 

Counting the occurrences / frequency of array elements

In Javascript, I'm trying to take an initial array of number values and count the elements inside it. Ideally, the result would be two new arrays, the first specifying each unique element, and the ...

stackoverflow.com

 

728x90