자바스크립트 코딩테스트 기본 메서드 모음👾

NANA·2025년 4월 12일
0
post-thumbnail

배열 메서드

  1. map() - 배열의 각 요소를 반환하여 새 배열 반환
const doubled = numbers.map(num => num * 2)
  1. filter() - 조건에 맞는 요소만 골라내어 새 배열 반환
const evens = numbers.filter(num => num % 2 === 0)
  1. reduce() - 배열의 요소를 줄여서 하나의 값으로 만듦
const sum = numbers.reduce((acc, curr) => acc + curr, 0)
  1. sort() - 배열을 정렬
numbers.sort((a, b) => a - b) // 오름차순 정렬
numbers.sort((a, b) => b - a) // 내림차순 정렬
  1. forEach() - 배열의 각 요소에 대해 함수 실행
numbers.forEach(num => console.log(num))
  1. find() - 조건에 맞는 첫 번째 요소 반환
const found = numbers.find(num => num > 10)
  1. some() - 배열에 조건을 만족하는 요소가 하나라도 있는지 확인
const hasEven = numbers.some(num => num % 2 === 0)
  1. every() - 배열에 모든 요소가 조건을 만족하는지 확인
const allPositive = numbers.every(num => num > 0)
  1. push(), pop() - 배열 끝에 요소 추가/제거
array.push(5) // 끝에 추가
const last = array.pop() // 끝에서 제거하고 반환
  1. shift(), unshift() - 배열 앞에서 요소 제거/추가
array.unshift(1) // 앞에 추가
const first = array.shift() // 앞에서 제거하고 반환
  1. slice() - 배열의 일부분 추출
const subArray = array.slice(2, 5) // 인덱스 2부터 4까지
  1. concat() - 배열들을 합쳐 새 배열 생성
const combined = array1.concat(arrat2)

문자열 메서드

  1. split() - 문자열을 구분자로 나누어 배열로 변환
const parts = str.split(',')
  1. join() - 배열을 문자열로 합치기
const joined = array.join('-')
  1. substring() - 문자열의 일부분 추출
const part = str.substring(2, 5)
  1. replace() - 문자열의 일부 교체
const newStr = str.replace('old', 'new')
  1. toLowerCase(), toUpperCase() - 소문자/대문자 변환
const lower = str.toLowerCase

수학 메서드

  1. Math.max(), Math.min() - 최댓값/최솟값 찾기
const max = Math.max(...numbers)
  1. Math.floor(), Math.ceil(), Math.round() - 정수로 반올림/올림/내림
const rounded = Math.floor(3.7) // 3
  1. Math.abs() - 절댓값
const absolute = Math.abs(-5) // 5

객체 메서드

  1. Object.keys(), Object.values() - 객체의 키/값 배열 반환
const keys = Object.keys(obj)
const values = Object.values(obj)
  1. Object.entries() - 객체의 [키,값] 쌍 배열 반환
const entries = Object.entries(obj)

집합/맵 자료구조

  1. Set - 중복 없는 집합
const uniqueValues = new Set(array)
const uniqueArray = [...uniqueValues]
  1. Map - 키-값 쌍을 저장하는 컬렉션
const frequency = new Map()
for (const num of array) {
	frequency.set(num, (frequency.get(num) || 0) + 1)
}
profile
고양이를 좋아하는 개발자입니다

0개의 댓글