[JS] Algorithm - 자주 쓰이는 구문 정리(22.02.06)
이채현
배열 중복값 개수 구하기
reduce()
reduce() 함수는, 배열의 값을 순회하면서 배열의 값을 특정 형태로 누적하는데 사용합니다.
1 | const inputNum = [1, 1, 2, 3, 4, 2, 1]; |
forEach()
1 | const cnt = {} |
forEach의 callback함수를 풀어쓰면 아래와 같다.
1 | if(cnt[x]) { |
즉, 처음에 배열의 첫 번째 값인 ‘1’이 들어오면, cnt[x] (cnt.1)은 undefined이다.
cnt[x]가 undefinded이므로 cnt에 key ‘1’를 추가하고 value 1을 세팅해준다.
이후 다시 ‘1’이 들어오면 cnt[1]은 존재하므로, cnt[1]값 1에 1을 더해준다.
배열에 1 ~ N 값 세팅하기
기본 반복문을 이용
1 | const arr = []; |
ES6의 Array from() and keys() 이용
1 | const arr = Array.from(Array(N).keys()); |
Spread를 이용한 방법
1 | const arr = [...Array(10).keys()]; |
1부터 시작하기 위해 from과 length property 이용
1 | const arr = Array.from({length: 10}, (_, i) => i + 1) |
단순 원하는 길이만큼 0으로 채우기
1 | const array = new Array(10001).fill(0); |
[JS] Algorithm - 자주 쓰이는 구문 정리(22.02.06)
https://devch.co.kr/categories/Algorithm/Javascript/JS-Algorithm-1-22-01-31/