1. 배열 순회 - forEach
1a = [1, 3, 45, 2, 10]23a.forEach((element, index) => {4console.log(element, index)5})67// 1 08// 3 19// 45 210// 2 311// 10 4
2. 문자열 분해 - split, join
1const str = 'Hello World'2const ret = str.split(' ')3console.log(ret) // [ 'Hello', 'World' ]4const a = ret.join(' 뭐시기 ')5console.log(a) // Hello 뭐시기 World
3. 정렬 - sort
1let numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]2numbers = numbers.sort((a, b) => a - b) // 오름차순3console.log(numbers) // [(1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9)]45numbers = numbers.sort((a, b) => (a - b) * -1) // 내림차순6console.log(numbers) // [(9, 6, 5, 5, 5, 4, 3, 3, 2, 1, 1)]
4. 필터링 - filter
1const numbers = [1, 2, 3, 4, 5, 6]2const ret = numbers.filter(ele => ele % 2 === 0)3console.log(ret) // [2, 4, 6]
5. 배열재가공 - map
1const numbers = [1, 2, 3, 4, 5]2const ret = numbers.map(el => el * 2)3console.log(ret) // [ 2, 4, 6, 8, 10 ]
1const numbers = [1, 2, 3, 4, 5]2let b = []3for (let a of numbers) {4b.push(a * 2)5}6console.log(b) // [ 2, 4, 6, 8, 10 ]
6. reduce
1const numbers = [1, 2, 3, 4, 5]2const ret = numbers.reduce((total, element) => total + element, 0)3console.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
1flowchart LR21 --> 231 --> 342 --> 453 --> 463 --> 5
- 탐색할 수 있는 방법 : 1 → 2 → 4 → 3 → 5
- 또는 : 1 → 3 → 5 → 2 → 4
1const graph = {21: [2, 3],32: [4],43: [4, 5],54: [],65: [],7}89const dfs = (here, visited = new Set()) => {10if (visited.has(here)) return11visited.add(here)12console.log(here)13graph[here].forEach(el => dfs(el, visited))14}1516dfs(1)17// 118// 219// 420// 321// 5
9. 이분탐색 - 이진탐색
1const a = [1, 2, 3, 4, 5, 6, 7, 8]2const bs = () => {3let lo = 04let hi = a.length - 15const target = 367while (lo <= hi) {8let mid = Math.floor((lo + hi) / 2)9if (a[mid] == target) {10console.log(target)11return '찾았다'12} else if (a[mid] > target) {13hi = mid + 114} else {15first = mid + 116}17}18return -119}2021const ret = bs() // 322console.log(ret)
10. 배열생성팁
1// 모든 원소가 0인 1차원배열2let a = Array(50).fill(0)3// console.log(a)45// 모든 원소가 1인 2차원배열6let b = Array(5)7.fill()8.map(el => Array(5).fill(1))9console.log(b)
11. DP - 피보나치
1const fibo = (idx, memo = {}) => {2if (idx <= 2) return 13if (idx in memo) return memo[idx]4memo[idx] = fibo(idx - 1, memo) + fibo(idx - 2, memo)5return memo[idx]6}7const ret = fibo(10)8console.log(ret) // 55 => 1, 1, 2, 3, 5, 8, 13, 21, 34, 55
12. 스와핑
1const arr = [1, 2, 3, 4, 5]2;[arr[1], arr[3]] = [arr[3], arr[1]]3console.log(arr) // [ 1, 4, 3, 2, 5 ]