🎉 berenickt 블로그에 온 걸 환영합니다. 🎉
Lang
JS 코테 12가지 로직

1. 배열 순회 - forEach

1
a = [1, 3, 45, 2, 10]
2
3
a.forEach((element, index) => {
4
console.log(element, index)
5
})
6
7
// 1 0
8
// 3 1
9
// 45 2
10
// 2 3
11
// 10 4

2. 문자열 분해 - split, join

1
const str = 'Hello World'
2
const ret = str.split(' ')
3
console.log(ret) // [ 'Hello', 'World' ]
4
const a = ret.join(' 뭐시기 ')
5
console.log(a) // Hello 뭐시기 World

3. 정렬 - sort

1
let numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
2
numbers = numbers.sort((a, b) => a - b) // 오름차순
3
console.log(numbers) // [(1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9)]
4
5
numbers = numbers.sort((a, b) => (a - b) * -1) // 내림차순
6
console.log(numbers) // [(9, 6, 5, 5, 5, 4, 3, 3, 2, 1, 1)]

4. 필터링 - filter

1
const numbers = [1, 2, 3, 4, 5, 6]
2
const ret = numbers.filter(ele => ele % 2 === 0)
3
console.log(ret) // [2, 4, 6]

5. 배열재가공 - map

1
const numbers = [1, 2, 3, 4, 5]
2
const ret = numbers.map(el => el * 2)
3
console.log(ret) // [ 2, 4, 6, 8, 10 ]
1
const numbers = [1, 2, 3, 4, 5]
2
let b = []
3
for (let a of numbers) {
4
b.push(a * 2)
5
}
6
console.log(b) // [ 2, 4, 6, 8, 10 ]

6. reduce

1
const numbers = [1, 2, 3, 4, 5]
2
const ret = numbers.reduce((total, element) => total + element, 0)
3
console.log(ret) // 15

7. 그외 기본문법

  • Find, findIndex, includes, substing, slice, Object.keys, Object.values, Object.entries, Math.round, Math.ceil, Math.floor, Math.abs

8. DFS

1
flowchart LR
2
1 --> 2
3
1 --> 3
4
2 --> 4
5
3 --> 4
6
3 --> 5
  • 탐색할 수 있는 방법 : 1 → 2 → 4 → 3 → 5
  • 또는 : 1 → 3 → 5 → 2 → 4
1
const graph = {
2
1: [2, 3],
3
2: [4],
4
3: [4, 5],
5
4: [],
6
5: [],
7
}
8
9
const dfs = (here, visited = new Set()) => {
10
if (visited.has(here)) return
11
visited.add(here)
12
console.log(here)
13
graph[here].forEach(el => dfs(el, visited))
14
}
15
16
dfs(1)
17
// 1
18
// 2
19
// 4
20
// 3
21
// 5

9. 이분탐색 - 이진탐색

1
const a = [1, 2, 3, 4, 5, 6, 7, 8]
2
const bs = () => {
3
let lo = 0
4
let hi = a.length - 1
5
const target = 3
6
7
while (lo <= hi) {
8
let mid = Math.floor((lo + hi) / 2)
9
if (a[mid] == target) {
10
console.log(target)
11
return '찾았다'
12
} else if (a[mid] > target) {
13
hi = mid + 1
14
} else {
15
first = mid + 1
16
}
17
}
18
return -1
19
}
20
21
const ret = bs() // 3
22
console.log(ret)

10. 배열생성팁

1
// 모든 원소가 0인 1차원배열
2
let a = Array(50).fill(0)
3
// console.log(a)
4
5
// 모든 원소가 1인 2차원배열
6
let b = Array(5)
7
.fill()
8
.map(el => Array(5).fill(1))
9
console.log(b)

11. DP - 피보나치

1
const fibo = (idx, memo = {}) => {
2
if (idx <= 2) return 1
3
if (idx in memo) return memo[idx]
4
memo[idx] = fibo(idx - 1, memo) + fibo(idx - 2, memo)
5
return memo[idx]
6
}
7
const ret = fibo(10)
8
console.log(ret) // 55 => 1, 1, 2, 3, 5, 8, 13, 21, 34, 55

12. 스와핑

1
const arr = [1, 2, 3, 4, 5]
2
;[arr[1], arr[3]] = [arr[3], arr[1]]
3
console.log(arr) // [ 1, 4, 3, 2, 5 ]