Array 만들기
// N x M 격자 (0으로 초기화)
const grid = Array.from({length: n}, () => Array(m).fill(0));
// N x M 격자 (false로 초기화)
const visited = Array.from({length: n}, () => Array(m).fill(false));
// 그래프 인접 리스트
const graph = Array.from({length: n}, () => []);
// 카운팅 배열
const count = Array(26).fill(0); // 알파벳 개수 세기
// DP 테이블
const dp = Array(n + 1).fill(0);
const dp2D = Array.from({length: n}, () => Array(m).fill(0));
// 숫자를 배열로
const n = 12345;
const arr = Array.from(String(n), Number); // [1, 2, 3, 4, 5]
const arr2 = String(n).split('').map(Number); // [1, 2, 3, 4, 5]
const arr3 = [...String(n)].map(Number); // [1, 2, 3, 4, 5]
// 문자열을 배열로
const str = "hello";
const arr = Array.from(str); // ['h', 'e', 'l', 'l', 'o']
const arr2 = [...str]; // ['h', 'e', 'l', 'l', 'o']
const arr3 = str.split(''); // ['h', 'e', 'l', 'l', 'o']
Slice
const arr = [1, 2, 3, 4, 5];
const str = "hello";
// 앞에서 n개 자르기
arr.slice(0, 3); // [1, 2, 3]
str.slice(0, 3); // "hel"
// 뒤에서 n개 자르기
arr.slice(-3); // [3, 4, 5]
str.slice(-3); // "llo"
// 중간 제거
arr.slice(0, 2).concat(arr.slice(3)); // [1, 2, 4, 5]
// 앞 n개 제거
arr.slice(2); // [3, 4, 5]
str.slice(2); // "llo"
// 문자열 뒤집기
[...str].reverse().join(''); // "olleh"
str.split('').reverse().join(''); // "olleh"
// 배열 특정 부분만 변경 (원본 유지)
[...arr.slice(0, 2), 'X', ...arr.slice(3)]; // [1, 2, 'X', 4, 5]
문자 찾기
const str = "hello world hello";
const count = str.split("hello").length - 1;
console.log(count); // 2
// 정규식 (조금 더 복잡하지만 많이 씀)
const count = (str.match(/hello/g) || []).length;
// replace 콜백 (교체도 같이 해야 할 때)
let count = 0;
str.replace(/hello/g, () => { count++; return "hi"; });
// indexOf 반복문 (그리디함)
let count = 0, index = 0;
while ((index = str.indexOf("hello", index)) !== -1) {
count++;
index++;
}
큐 구현
class Queue {
items = []; front = 0;
push = item => this.items.push(item);
pop = () => this.items[this.front++];
isEmpty = () => this.front >= this.items.length;
size = () => this.items.length - this.front;
peek = () => this.items[this.front];
}
해시 (Object)
// 객체 메서드 3종 세트
const obj = { name: '홍길동', age: 25, city: '서울' }
// 키만
Object.keys(obj) // ['name', 'age', 'city']
// 값만
Object.values(obj) // ['홍길동', 25, '서울']
// 키-값 쌍
Object.entries(obj) // [['name', '홍길동'], ['age', 25], ['city', '서울']]
// 1. some - 하나라도 있으면 true
Object.values(obj).some(v => v >= 0) // true
// 2. every - 모두 0 이상이면 true
Object.values(obj).every(v => v >= 0) // false
// 3. filter - 0 이상인 값들만
Object.values(obj).filter(v => v >= 0) // [2]
// 4. find - 첫 번째로 찾은 값
Object.values(obj).find(v => v >= 0) // 2
// 응용
// value로 key 찾기
const findKey = (obj, value) => Object.keys(obj).find(k => obj[k] === value);
const findKeys = (obj, value) => Object.keys(obj).filter(k => obj[k] === value);
// entries 활용
// 순회하면서 키-값 둘 다 사용
for (let [key, value] of Object.entries(obj)) {
console.log(key, value);
}
중복제거 (Set)
// 배열 중복 제거 (가장 자주 사용)
const unique = [...new Set(array)];
// 존재 확인 (O(1))
const visited = new Set();
if (visited.has(item)) return;
visited.add(item);
스프레드 연산자 복사
- 객체 복사
// 얕은 복사 (shallow copy)
const original = { a: 1, b: 2, c: 3 }
const copy = {...original}
// 속성 추가/덮어쓰기
const updated = {...original, d: 4, a: 10}
// { a: 10, b: 2, c: 3, d: 4 }
// 여러 객체 합치기
const obj1 = { a: 1, b: 2 }
const obj2 = { c: 3, d: 4 }
const merged = {...obj1, ...obj2}
// { a: 1, b: 2, c: 3, d: 4 }
- 배열 복사
// 배열 복사
const arr = [1, 2, 3]
const copyArr = [...arr]
// 배열 합치기
const arr1 = [1, 2]
const arr2 = [3, 4]
const merged = [...arr1, ...arr2] // [1, 2, 3, 4]
// 요소 추가
const added = [...arr, 4, 5] // [1, 2, 3, 4, 5]
- 깊은 복사
// 1순위: structuredClone (환경 지원하면)
const copy = structuredClone(obj)
// 2순위: JSON 방식 (가장 무난)
const copy = JSON.parse(JSON.stringify(obj))
- 코테에서 자주 쓰이는 패턴
// 객체 복사 후 수정
for (let i = 0; i < n; i++) {
let newHash = {...hashObj} // 매번 새로 복사
// newHash 수정...
}
// 배열 복사 후 정렬
const sorted = [...arr].sort((a, b) => a - b) // 원본 보존
bfs (너비 우선 탐색)
게임 맵 최단 거리
https://school.programmers.co.kr/learn/courses/30/lessons/1844?language=javascript
class Queue {
items = [];
front = 0;
rear = 0;
push(item) {
this.items.push(item);
this.rear++;
}
first() {
return this.items[this.front]
}
last() {
return this.items[this.rear - 1]
}
pop() {
return this.items[this.front++]
}
isEmpty() {
return this.front === this.rear;
}
}
function solution(maps) {
const move = [[-1,0], [0,-1], [0,1], [1,0]]
const n = maps.length
const m = maps[0].length
const dist = Array.from({length:n}, () => Array(m).fill(-1))
function bfs(start) {
const q = new Queue()
q.push(start);
dist[start[0]][start[1]] = 1
while (!q.isEmpty()) {
const here = q.pop();
for (const [dx,dy] of move) {
const row = here[0] + dx;
const column = here[1] + dy;
if (row < 0 || row >= n || column < 0 || column >=m ) {
continue;
}
if (maps[row][column] === 0) {
continue;
}
if (dist[row][column] === -1) {
q.push([row, column]);
dist[row][column] = dist[here[0]][here[1]] + 1
}
}
}
// return dist
}
bfs([0,0])
return dist[n-1][m-1];
}
dfs (깊이 우선 탐색)
컴퓨터 연결 네트워크 갯수
https://school.programmers.co.kr/learn/courses/30/lessons/43162
function dfs(computers, visited, node) {
visited[node] = true //현재 노드 방문 처리
for (let idx = 0; idx<computers[node].length; idx++) {
if (computers[node][idx] && !visited[idx]) { // 연결되어 있고 방문하지 않은 노드라면
dfs(computers, visited, idx) //해당 노드 방문
}
}
}
function solution(n, computers) {
var answer = 0;
const visited = Array(n).fill(false)
for (let i=0; i<n; i++) {
if(!visited[i]) { //아직 방문 하지 않은 노드라면
dfs(computers,visited,i) //dfs로 연결된 노드들을 모두 방문하면서 네트워크 개수 증가
answer++;
}
}
return answer;
}
백트래킹(가지치기)
피로도
https://school.programmers.co.kr/learn/courses/30/lessons/87946
// 백트래킹을 위한 DFS
function dfs(curK, cnt, dungeons, visited) {
let answerMax = cnt;
for (let i = 0; i < dungeons.length; i++) {
// 유망함수
// 1. 현재 피로도(curK)가 i번째 던전의 최소 필요 피로도보다 크거나 같고, i번째 던전을 방문한 적이 없다면
if (curK >= dungeons[i][0] && visited[i] === 0) {
visited[i] = 1
// 현재까지의 최대 탐험 가능 던전 수와 i번째 던전에서 이동할 수 있는 최대 탐험 가능 던전 수 중 큰 값을 선택하여 업데이트
answerMax = Math.max(answerMax, dfs(curK - dungeons[i][1], cnt + 1, dungeons, visited))
visited[i] = 0;
}
}
return answerMax;
}
function solution(k, dungeons) {
const visited = Array(dungeons.length).fill(0)
const answerMax = dfs(k, 0, dungeons, visited)
return answerMax;
}
정렬 (sort 메소드)
1. 숫자 정렬
arr.sort((a, b) => a - b); // 오름차순 ⭐
arr.sort((a, b) => a > b ? 1 : -1); // 동일함
arr.sort((a, b) => b - a); // 내림차순 ⭐
arr.sort((a, b) => a > b ? -1 : 1);
2. 문자열 정렬
arr.sort(); // 오름차순 (기본)
arr.sort().reverse(); // 내림차순
3. 객체 배열 정렬
// 숫자 속성
arr.sort((a, b) => a.score - b.score);
// 문자 속성
arr.sort((a, b) => a.name.localeCompare(b.name));
4. 2차원 배열 정렬
// 첫 번째 요소 기준
arr.sort((a, b) => a[0] - b[0]);
// 두 번째 요소 기준
arr.sort((a, b) => a[1] - b[1]);
5. 복합 정렬 (다중 조건) ⭐⭐
// 방법1: if문
arr.sort((a, b) => {
if (a[0] !== b[0]) return a[0] - b[0]; // 1순위
return a[1] - b[1]; // 2순위
});
// 방법2: || 연산자 (더 간결!)
arr.sort((a, b) => a[0] - b[0] || a[1] - b[1]);
6. 특수 정렬
// 절댓값
arr.sort((a, b) => Math.abs(a) - Math.abs(b));
// 배열 길이
arr.sort((a, b) => a.length - b.length);
// 짝수 우선
arr.sort((a, b) => (a % 2) - (b % 2));
7. 원본 보존 (필요시)
const sorted = [...arr].sort((a, b) => a - b); // ⭐
자주 실수하는 것
// ❌ 숫자 정렬 시 비교함수 안 쓰면 망함!
[1, 2, 10].sort(); // [1, 10, 2] 문자열로 변환되어 정렬
// ✅ 반드시 비교함수 사용
[1, 2, 10].sort((a, b) => a - b); // [1, 2, 10]
실전 예시
// 예: [[1,4], [3,5], [0,6], [5,7]] 시작시간 순 정렬
intervals.sort((a, b) => a[0] - b[0]);
// 예: 거리가 가까운 순 정렬
points.sort((a, b) => {
const distA = a[0]**2 + a[1]**2;
const distB = b[0]**2 + b[1]**2;
return distA - distB;
});
2진법
const num = 255;
num.toString(2); // "11111111" (2진법)
num.toString(8); // "377" (8진법)
num.toString(10); // "255" (10진법)
parseInt("1010", 2); // 10
parseInt("77", 8); // 63
가장 많이 쓰이는 Math 메서드
1. Math.floor(), Math.ceil(), Math.round()
// 내림
Math.floor(4.7); // 4
Math.floor(-4.7); // -5
// 올림
Math.ceil(4.3); // 5
Math.ceil(-4.3); // -4
// 반올림
Math.round(4.5); // 5
Math.round(4.4); // 4
2. Math.max(), Math.min()
// 최댓값, 최솟값
Math.max(1, 3, 2); // 3
Math.min(1, 3, 2); // 1
// 배열에서 사용 (spread 연산자)
const arr = [1, 5, 3, 9, 2];
Math.max(...arr); // 9
Math.min(...arr); // 1
3. Math.abs()
// 절댓값
Math.abs(-5); // 5
Math.abs(5); // 5
Math.abs(-3.14); // 3.14
4. Math.pow(), Math.sqrt()
// 거듭제곱
Math.pow(2, 3); // 8 (2의 3승)
2 ** 3; // 8 (ES6 거듭제곱 연산자)
// 제곱근
Math.sqrt(16); // 4
Math.sqrt(2); // 1.414...
5. Math.trunc()
// 소수점 버림 (정수 부분만)
Math.trunc(4.9); // 4
Math.trunc(-4.9); // -4
- 활용 예시
좌표 거리 계산
function getDistance(x1, y1, x2, y2) {
return Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
}
나누기 몫 구하기
const quotient = Math.floor(10 / 3); // 3
배열 평균 구하기
const arr = [1, 2, 3, 4, 5];
const avg = arr.reduce((a, b) => a + b) / arr.length;
Math.round(avg); // 반올림
'JS 코딩테스트' 카테고리의 다른 글
| [JS hash] object vs Map vs Set 차이 (0) | 2025.09.23 |
|---|---|
| [백준] 11866 요세푸스 (0) | 2025.08.17 |
| [JS코테] javascript로 큐 구현 (1) | 2025.08.17 |
| [JS 코테] LeetCode 2722. Join Two Arrays by ID (0) | 2025.05.05 |
| [LeetCode] 2667 create-hello-world-function (2) | 2024.11.12 |