자바스크립트/표준 내장 객체

[자바스크립트] Array 객체 정리

Hun's blog 2026. 5. 24. 17:16

실무에서 React를 다루며 관련 문법은 익숙해졌으나, 자바스크립트 기본기는 등한시했음을 느꼈다.

AI 생성 코드를 리뷰할 때도 React나 JSX보다 자바스크립트 로직에서 병목이 발생했다.

 

이를 보완하고자 프로그래머스 기초 문제를 풀며 자바스크립트 구현 스킬을 향상하려 한다. 앞으로 문제 풀이와 타인의 코드를 참고해 유용한 함수와 메소드를 기록할 예정이며, 이번 편에서는 Array 객체를 정리한다.


1. 기본 조작 및 탐색

push() / pop()

배열 맨 끝에 요소를 추가하거나 제거하는 가장 기초적인 기능

let arr = [];

arr.push(1);
console.log(arr); // [ 1 ]

arr.pop();
console.log(arr); // []

 

includes() / indexOf() / lastIndexOf()

특정 값이 배열에 있는지 확인하고 위치를 찾는 기본 탐색 기능

let arr = [0, 1, 2, 1];

console.log(arr.includes(1)); // true (1 값 포함 여부)
console.log(arr.indexOf(1)); // 1 (앞에서 부터 찾음)
console.log(arr.indexOf(1, 2) // 3 (2번 인덱스 부터 찾음)
console.log(arr.lastIndexOf(1)); // 3 (뒤에서 부터 찾음)

 


2. 순회 및 필터링

forEach()

단순 반복 조작용으로 for 루프를 대체하는 기본 순회 메소드

let arr = [[1, 2], [3, 4], [5, 6]];

// value: 배열에 담긴 요소 (옵션) -
// index: 순회중인 인덱스 번호 (옵션)
// array: 원본 배열 (옵션)
// 아무 인자를 포함하지 않으면 arr.length 만큼 순회
arr.forEach((value, index, array) => console.log(value, index, array));
// [ 1, 2 ] 0 [ [ 1, 2 ], [ 3, 4 ], [ 5, 6 ] ]
// [ 3, 4 ] 1 [ [ 1, 2 ], [ 3, 4 ], [ 5, 6 ] ]
// [ 5, 6 ] 2 [ [ 1, 2 ], [ 3, 4 ], [ 5, 6 ] ]

 

map()

요소를 가공해 새로운 배열을 만드는 메소드

let arr = [1, 2, 3, 4, 5];

// value: 배열에 담긴 요소 (옵션) -
// index: 순회중인 인덱스 번호 (옵션)
// array: 원본 배열 (옵션)
let new_arr = arr.map((value, index, array) => value * index);
console.log(new_arr);
// [0, 2, 6, 12, 20]

 

filter()

조건을 만족하는 요소만 걸러내어 새로운 배열을 만드는 메소드

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

// 짝수만 필터링
const evens = numbers.filter((value) => value % 2 === 0);
console.log(evens);
// 출력: [2, 4]


const words = ["사과", "바나나", "수박", "파인애플"];

// 글자 수가 3글자 이상인 단어만 필터링
const longWords = words.filter((word) => word.length >= 3);
console.log(longWords);
// 출력: ["바나나", "파인애플"]

3. 배열 잘라내기 및 수정

slice()

원본 배열은 건드리지 않고, 필요한 부분만 복사해서 가져오는 메소드

const months = ["1월", "2월", "3월", "4월", "5월"];

console.log(months.slice(2));
// ["3월", "4월", "5월"]

console.log(months.slice(2, 4));
// ["3월", "4월"]

console.log(months.slice(1, 5));
// ["2월", "3월", "4월", "5월"]

console.log(months.slice(-2));
// ["4월", "5월"]

console.log(months.slice(2, -1));
// ["3월", "4월"]

console.log(months.slice());
// ["1월", "2월", "3월", "4월", "5월"]

 

splice()

원본 배열을 직접 수정(요소 삭제 및 삽입)함.

const months = ["1월", "3월", "4월", "5월"];

// 인덱스 1번 자리에 아무것도 지우지 않고(0) "2월"을 추가
months.splice(1, 0, "2월");
console.log(months);
// 출력: ["1월", "2월", "3월", "4월", "5월"]

// 인덱스 4번 자리(현재 "5월")의 요소 1개를 지우고(1) 그 자리에 "5월"을 다시 넣음 (결과적으로 교체)
// 만약 "5월"을 지우고 다른 걸 넣고 싶다면 세 번째 인자를 바꾸면 돼.
months.splice(4, 1, "5월");
console.log(months);
// 출력: ["1월", "2월", "3월", "4월", "5월"]

// 인덱스 2번 자리부터 모든 요소를 지움
months.splice(2);
console.log(months);
// 출력 : ["1월", "2월"]

// 인덱스 0번 자리의 요소 1개를 지움
months.splice(0, 1);
console.log(months);
// 출력 : ["2월"]

4. 정렬 및 반전

sort()

배열 요소를 정렬하는 메소드

// 문자열 배열을 정렬할 때
const fruits = ["바나나", "딸기", "사과", "아보카도"];
fruits.sort();

console.log(fruits);
// 출력: ["딸기", "바나나", "사과", "아보카도"]

// 숫자르 정렬할 때
const numbers = [4, 2, 5, 1, 3, 10];
numbers.sort();

console.log(numbers);
// 출력: [1, 10, 2, 3, 4, 5]

// 숫자를 올바르게 정렬하려면 비교 함수를 제공해야 함
numbers.sort((a, b) => a - b);
console.log(numbers);
// 출력: [1, 2, 3, 4, 5, 10]

numbers.sort((a, b) => b - a);
console.log(numbers);
// 출력: [10, 5, 4, 3, 2, 1]

 

reverse()

배열 순서를 뒤집는 메소드

const directions = ["동", "서", "남", "북"];
directions.reverse();

console.log(directions); 
// 출력: ["북", "남", "서", "동"]

// reverse 는 원본 배열도 뒤집어 버림
const original = ["a", "b", "c"];
const reversed = original.reverse();

console.log(original);
// 출력: ["c", "b", "a"]

console.log(reversed);
// 출력: ["c", "b", "a"]

// 원본을 유지하고 싶을 경우에는 다음과 같은 방식을 활용할 것
const reversed = [...original].reverse();

5. 가공 및 최종 연산

join()

배열을 하나의 문자열로 결합하는 메소드

const elements = ["Fire", "Air", "Water"];

// 1. 인자를 생략하면 기본값으로 쉼표(,)로 연결됨
const result1 = elements.join();
console.log(result1); 
// 출력: "Fire,Air,Water"

// 2. 빈 문자열('')을 넣으면 공백 없이 싹 다 붙음
const result2 = elements.join('');
console.log(result2); 
// 출력: "FireAirWater"

// 3. 원하는 구분자(공백, 대시 등)를 자유롭게 넣을 수 있음
const result3 = elements.join(' - ');
console.log(result3); 
// 출력: "Fire - Air - Water"

 

reduce()

배열을 하나의 값으로 축소(누적 연산) 하는 메소드

const numbers = [1, 2, 3, 4];

// 초기값 0에서 시작해서 배열의 숫자를 하나씩 더해나감
// previousValue(누적값): 이전 콜백 함수가 반환한 누적값. acc 로 줄여 사용
// currentValue (현재값): 현재 배열에서 순회하며 처리중인 요소의 값. cur로 줄여 사용
// currentIndex: 현재 인덱스
// array: 원본배열
const total = numbers.reduce((previousValue, currentValue, currentIndex, array) => {
  return previousValue + currentValue;
}, 0);

console.log(total);
// 결과: 10