[05.15-05.18/WEIL] 코딩테스트 전전날 보는 JavaScript

CHO WanGi·2025년 5월 18일
9

KRAFTON JUNGLE 8th

목록 보기
55/89

WEIL은 WeekEnd I Learnedd...

JavaScript로 코테를 준비하면서 자주사용한 메서드들을 정리하려고 한다.

1. 배열 순회 및 index : forEach

python의 enumerate 와 같은 기능을 한다

a = [1, 3, 45, 2, 10];

a.forEach((elem , idx)) => {
	console.log(elem, idx); // 1 0 ....
}

2. 문자열 분할 및 조합 : join, split

const str = "Hello World";
const ret = str.split(" ")
console.log(ret); // [ 'Hello', 'World' ]


const a = ret.join(' ');
console.log(a); // Hello World
const b = ret.join("bar")
console.log(b); // HellobarWorld

3. 알아두면 좋은 각종 메서드

find(): 배열에서 특정 조건을 만족하는 첫번째 요소

const nums = [1, 2, 3, 4]
const even = nums.find((e) => e % 2 == 0);
console.log(even); // 2

some() : 배열에서 하나라도 콜백함수로 넘겨준 조건 만족시 True리턴

const array = [1, 2, 3, 4, 5];

const even = (element) => element % 2 === 0;

console.log(array.some(even));
// expected output: true

findIndex() : 배열에서 특정 조건을 만족하는 첫번째 요소의 인덱스 반환

const nums = [1, 2, 3, 4]
const even = nums.findIndex((e) => e % 2 == 0);
console.log(even); // 1

includes() : 배열에 특정 요소가 있는지 True or False 반환

파이썬의 in 연산자와 동일한 역할

const nums = [1, 2, 3, 4]
console.log(nums.includes(3)) // true
console.log(nums.includes(5)) // false

substring() : 문자열의 시작 인덱스부터 끝 인덱스 - 1 까지 반환

const str = "ABCDE";
console.log(str.substring(1, 3)); //BC

startsWith() : 특정 단어로 시작하는 문자열 찾기

const str1 = "Saturday night plans";

console.log(str1.startsWith("Sat"));
// Expected output: true

slice() : 배열의 시작 인덱스 부터 끝 인덱스 -1 까지 복사하여 반환

복사기에 원본은 그대로 유지가 된다

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

splice() : 배열의 특정 위치 요소 삭제, 추가

삭제, 추가 둘다 가능한 만능 메서드인데 단 원본 바꿈.

  • 삭제
    배열의 특정 idx 요소 한개를 삭제하고 싶을때 유용하게 쓰인다
let fruits = ['apple', 'banana', 'cherry'];
fruits.splice(1, 1); // idx 1 부터 1개 삭제
console.log(fruits);  // ['apple', 'cherry']
  • 추가
let fruits = ['apple', 'banana', 'cherry'];
fruits.splice(1, 0, 'kiwi');
console.log(fruits);  // ['apple', 'kiwi', 'banana', 'cherry']

Object.keys / values/ entries

Object.keys: 객체(Map, Array) 의 key값만 가져옴

Object.values: 객체(Map, Array) 의 value값만 가져옴

배열도 객체라서 사용가능한데 , Object.keys()에 인자로 배열을 넘기면 인덱스가 나옴.

const myObject = {
    name: '싹쓰리',
    enName: 'SSAK3',
    members: ['유두래곤', '린다G', '비룡'],
    genre: 'Dance & pop',
    agency: 'MBC',
    making: '놀면뭐하니?'
}

const myKeys = Object.keys(myObject);
const myVals = Object.values(myObject);

console.log(myVals);
// ['싹쓰리','SSAK3',[ '유두래곤', '린다G', '비룡' ],'Dance & pop','MBC','놀면뭐하니?']
console.log(myKeys);
// ["name", "enName", "members", "genre", "agency", "making"]

Object.entries : 객체를 배열로 변환하는 메서드

{Key : value} ⇒ [key, value] 이렇게 바꾸어주어서, Array 메서드들(filter, find, forEach)을 사용할 수 있다.

const myObject = {
  name: '싹쓰리',
  enName: 'SSAK3',
  members: ['유두래곤', '린다G', '비룡'],
  genre: 'Dance & pop',
  agency: 'MBC',
  making: '놀면뭐하니?'
}

const maArrs = Object.entries(myObject);

console.log(maArrs);
/*
[
  [ 'name', '싹쓰리' ],
  [ 'enName', 'SSAK3' ],
  [ 'members', [ '유두래곤', '린다G', '비룡' ] ],
  [ 'genre', 'Dance & pop' ],
  [ 'agency', 'MBC' ],
  [ 'making', '놀면뭐하니?' ]
]
*/

console.log(maArrs.filter((elem) => elem[0] === 'name')); // [ [ 'name', '싹쓰리' ] ]
console.log(maArrs.find((elem) => elem[0] === 'name')); // [ 'name', '싹쓰리' ]

Math

  1. Math.round : 반올림
  2. Math.ceil : 올림
  3. Math.floor : 버림
  4. Math.ads : 절댓값

배열 활용

1. 정렬하기 : sort()

sort에 아무 인자도 안넘겨주면 js는 문자열의 UniCode 순이기에 의도한 순서가 아닐 수 있다.
반드시 인자를 넘겨줍시다.

let numbers = [2, 5, 21, 1, 4, 7, 8, 9];
numbers = numbers.sort((a, b) => a - b); // 오름 차순 정렬
console.log(numbers); //   [1, 2, 4,  5, 7, 8, 9, 21 ]

2. 특정 요소 찾기 : filter()

let numbers = [2, 5, 21, 1, 4, 7, 8, 9];
numbers = numbers.sort((a, b) => a - b);
console.log(numbers.filter((elem) => elem % 2 == 0)) // 짝수만 찾기 2 4 8

3. 배열의 각 요소에 반복작업 : map()

let numbers = [2, 5, 21, 1, 4, 7, 8, 9];
const ret = numbers.map(e => e * 2) // 새로운 배열 생성
console.log(ret); // [4, 10, 42, 2,8, 14, 16, 18]

4. 배열 내 전체 요소의 총합 구하기 : reduce()

const number = [1, 2, 3, 4, 5]
const ret = number.reduce((total, e) => total + e); // total 변수에 배열 요소 모두 더하기
const ret_100 = number.reduce((total, e) => total + e + 100); // total 변수에 배열 요소 모두 더하기 + 100

console.log(ret); // 15

DFS & BFS

  • DFS
  1. 시작 노드를 방문처리
  2. 시작 노드의 인접 노드들을 재귀적으로 DFS
const graph = {
  1: [2, 3],
  2: [4],
  3: [4, 5],
  4: [],
  5: []
};

let visited = [];
function dfs(start) {
  if (visited.includes(start)) {
    return;
  }
  visited.push(start);
  console.log(start)
  graph[start].forEach(e => dfs(e));
  /* for(let i = 0; i < graph[start].length; i++){
		  dfs(graph[start][i]);
	  } */
  
  /*
  	for(let neighbor of graph[start]){
    	dfs(neighbor);
    }
  */
  }

dfs(1);
  • BFS
  1. 시작 노드를 큐에 삽입 및 방문처리
  2. 큐에서 꺼내기(shift)
  3. 꺼낸 큐의 인접 노드 중 방문하지 않는 노드들 삽입
  4. 큐가 빌때까지 이를 반복
function BFS(graph, start, visited) {
  const queue = [];
  queue.push(start);
  visited[start] = true;

  while (queue.length != 0) {
    const v = queue.shift();
    console.log(v);

    for (const node of graph[v]) {
      if (!visited[node]) {
        queue.push(node);
        visited[node] = true;
      }
    }
  }
}
let visited = new Array(5).fill(false)

BFS(graph, graph[0], visited)

이분 탐색

const a = [1, 2, 3, 4, 5, 6, 7, 8, 9];
let start = 0
let end = a.length - 1;
let mid

function binary_search(target) {
  while (start <= end) {
    mid = Math.floor((start + end) / 2);
    if (a[mid] == target) {
      console.log(target);
      return;
    } else if (a[mid] > target) {
      end = mid - 1
    } else {
      start = mid + 1
    }
  }
}

binary_search(4);

vistied, 2차원 배열 등 배열 생성

let a = Array(50).fill(0); // 0이 50개 들어간 1차원 배열


let apt = Array.from({length : 5}, ()=> Array(4).fill(0))// 5(row) * 4(col) 짜리 2차원 배열
console.log(apt)
/*
[
  [ 0, 0, 0, 0 ],
  [ 0, 0, 0, 0 ],
  [ 0, 0, 0, 0 ],
  [ 0, 0, 0, 0 ],
  [ 0, 0, 0, 0 ]
]
 */

DP

피보나치


function fibo(N, memo = []) {
  if (N <= 2) {
    return 1;
  }

  if (N in memo) {
    return memo[N]
  }
  memo[N] = fibo(N - 1, memo) + fibo(N - 2, memo);
  return memo[N]

}

console.log(fibo(10));

하노이 탑

function solution(n) {
    var answer = [];
    function move(start, end){
        answer.push([start, end])
    }
    
    function hanoi(n, start, end, mid){
        if(n == 1){
            move(start, end)
        } else {
            hanoi(n - 1, start, mid, end);
            move(start, end);
            hanoi(n - 1 , mid, end, start);   
        }
    }
    hanoi(n, 1, 3, 2)
    return answer;
}

배열 요소간 swap

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

Map(해시)초기화

초기화 없이 값부터 냅다 집어넣으려면 에러가 발생해서 if문으로 null 체크 후 value값을 더하는데
이를 or 연산자를 활용해서 좀 더 쌈뽕하게 코딩 가능.

  • 원리

보통 초기화가 안된채로 선언하면 undefined를 반환하는데,
undefined는 falsy한 값이라 0 이 되고,
초기화가 안된 상태라면 0 || 0 이라서 0을 반환하게되고

이미 값이 집어넣어진 상태라면 xCounts[point[0]] || 0 라서 xCounts[point[0]] 를 반환하게 된다.

 for(let elem of nums){
        if(map[elem] == null){
            map[elem] = 0
        }
        map[elem]++;
    }


    for (const point of v) {
        xCounts[point[0]] = (xCounts[point[0]] || 0) + 1;
        yCounts[point[1]] = (yCounts[point[1]] || 0) + 1;
    }

Priorty Queue(MinHeap)

class Node{
        constructor(val, priority){
            this.val = val // 노드 값
            this.priority = priority // 우선순위
        }
    }
    
class PriorityQueue{
    constructor(){
        this.values = []; // 우선순위 큐
    }
    enqueue(val, priority){
        let newNode = new Node(val, priority);
        this.values.push(newNode); // 삽입
        this.bubbleUp(); // 우선순위에 따른 재조정
    }
    dequeue(){
        let min = this.values[0] // 가장 앞에 있는 원소
        let end = this.values.pop();
        if(this.values.length > 0){
            this.values[0] = end; // pop 후 제일 앞에 있던 원소
            this.bubbleDown(); // 재조정
        }
        return min; 
    }

    bubbleUp(){
        let idx = this.values.length - 1;
        const element = this.values[idx]; // 마지막 원소
        while(idx > 0){
            let parentIdx = Math.floor((idx - 1) / 2) // 부모노드
            let parent = this.values[parentIdx];
            if(element.priority >= parent.priority) break; // 최소힙이니 부모가 자기보다 값이 작으면 조건 만족
            this.values[parentIdx] = element; // 부모, 자식 교환
            this.values[idx] = parent;
            idx = parentIdx;

        }
    }
    bubbleDown(){
        let idx = 0;
        const length = this.values.length;
        const element = this.values[0];
        while(true){
            let leftChildIdx = 2 * idx + 1; //0 Idx 기반, 1 더해주기
            let rightChildIdx = 2 * idx + 2;
            let leftChild, rightChild;
            let swap = null;

            if(leftChildIdx < length){
                leftChild = this.values[leftChildIdx];
                if(leftChild.priority < element.priority){
                  // 왼쪽 자식의 우선순위가 더 작으면 현재 요소보다 앞으로 와야함.
                  // 교체 대상으로 지정
                    swap = leftChildIdx;
                }
            }

            if(rightChildIdx < length){
                rightChild = this.values[rightChildIdx];
                 if ((swap === null && rightChild.priority < element.priority) ||(swap !== null && rightChild.priority < leftChild.priority)){
                   //1. 오른쪽 자식의 우선순위가 더 낮은 경우
                   //2. 오른쪽 자식의 우선순위가 왼쪽 자식보다 더 낮은 경우
                    swap = rightChildIdx;
                }
            }
            if(swap == null) break;
            this.values[idx] = this.values[swap];
            this.values[swap] = element;
            idx = swap;
        }
    }
}
profile
제 Velog에 오신 모든 분들이 작더라도 인사이트를 얻어가셨으면 좋겠습니다 :)

0개의 댓글