Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
Tags
- R데이터형태
- getline
- barplot in r
- 탈출문자
- 값추가
- 그래픽
- 배열삭제
- 이용현황분석
- 이스케이프시퀀스
- plot in r
- 그대로 출력하기
- setstate
- await
- 버스분석
- vetor
- DataFrame
- R 그래프
- react #회원가입 #비밀번호비교
- 데이터분석
- 광명시버스분석
- 백준 11718
- useState
- barplot
- 백준 10172
- 10172
- 백준
- asynchronization
- 값삭제
- React
- 배열추가
Archives
- Today
- Total
devlog_zz
배열의 각 항목별 개수 세기 본문
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
'Front End > Javascript' 카테고리의 다른 글
[ Javascript ] 소수인지 판별하기, Math.sqrt(n) 제곱근 활용 (0) | 2023.02.11 |
---|---|
n진수로 변환하기 toString() , parseInt() (0) | 2023.02.11 |
javascript sort() 와 sort((a, b) => a - b) 차이 (0) | 2022.11.28 |
?? 와 || 의 차이점 - falsy, truthy 개념 (0) | 2022.11.01 |
+10%, -10% 금액에서 1000원 이하 올림 (0) | 2022.07.31 |
Comments