[JavaScript] 배열

이건·2023년 12월 28일
0

Front-end

목록 보기
13/15
post-thumbnail

배열(Array)

배열은 여러 데이터를 순차적으로 저장하는 자료구조로, 여러가지 메서드를 통해 데이터를 쉽게 조작할 수 있다.

배열 선언

배열은 대괄호 [] 또는 new Array() 생성자를 사용하여 선언할 수 있다.

const arr1 = new Array();
const arr2 = [1, 2];

인덱스 위치

배열의 각 요소는 인덱스로 접근할 수 있다.

const fruits = ['🍎', '🍌'];
console.log(fruits); // ['🍎', '🍌']
console.log(fruits.length); // 2
console.log(fruits[0]); // 🍎
console.log(fruits[1]); // 🍌
console.log(fruits[2]); // error
console.log(fruits[fruits.length - 1]); // 🍌

배열 순회

배열의 모든 요소를 순회하는 방버은 여러 가지가 있다.

// a. for 문
for (let i = 0; i < fruits.length; i++) {
  console.log(fruits[i]);
}

// b. for...of 문
for (let fruit of fruits) {
  console.log(fruit);
}

// c. forEach 메서드
fruits.forEach((fruit) => console.log(fruit));

추가, 삭제, 복사

배결의 끝이나 시작 부분에 요소를 추가하거나 제거할 수 있다.

// push 메서드: 배열의 끝에 요소 추가
fruits.push('🍓', '🍑');
console.log(fruits); // ['🍎', '🍌', '🍓', '🍑']

// pop 메서드: 배열의 끝에서 요소 제거
const poped = fruits.pop();
fruits.pop();
console.log(fruits); // ['🍎', '🍌']

// unshift 메서드: 배열의 시작 부분에 요소 추가
fruits.unshift('🍓', '🍋');
console.log(fruits); // ['🍓', '🍋', '🍎', '🍌']

// shift 메서드: 배열의 시작 부분에서 요소 제거
fruits.shift();
fruits.shift();
console.log(fruits); // ['🍎', '🍌']

// splice 메서드: 원하는 인덱스에서 요소를 추가하거나 제거
// shift, unshift는 pop, push보다 매우 느리다.
fruits.push('🍓', '🍑', '🍋');
console.log(fruits); // ['🍎', '🍌', '🍓', '🍑', '🍋']
fruits.splice(1, 1);
console.log(fruits); // ['🍎', '🍓', '🍑', '🍋']
fruits.splice(1, 0, '🍏', '🍉');
console.log(fruits); // ['🍎', '🍏', '🍉', '🍓', '🍑', '🍋']

// concat 메서드: 두 배열 결합
const fruits2 = ['🍐', '🥥'];
const newFruits = fruits.concat(fruits2);
console.log(newFruits); // ['🍎', '🍏', '🍉', '🍓', '🍑', '🍋', '🍐', '🥥']

검색

배열 내 특정 요소의 인덱스를 찾거나 포함 여부를 확인할 수 있다.

// indexOf 메서드: 특정 요소의 첫 번째 인덱스 반환
console.log(fruits) // ['🍎', '🍏', '🍉', '🍓', '🍑', '🍋']
console.log(fruits.indexOf('🍎')); // 0
console.log(fruits.indexOf('🍉')); // 2
console.log(fruits.indexOf('🥥')); // -1 (없으면 -1 반환)

// includes 메서드: 특정 요소의 포함 여부 확인
console.log(fruits.includes('🍉')); // true
console.log(fruits.includes('🥥')); // false

// lastIndexOf 메서드: 특정 요소의 마지막 인덱스 반환
fruits.push('🍎');
console.log(fruits.lastIndexOf('🍎')); // 마지막 '🍎'의 인덱스 반환

Array APIs

JavaScript 배열은 다양한 내장 API를 제공하여, 데이터를 조작하고 처리하는 데 필요한 다양한 기능을 지원한다.

join()

join() 메서드를 사용하여 배열의 모든 요소를 문자열로 변환할 수 있다.

const fruits = ['apple', 'banana', 'orange'];
const result = fruits.join(', ');
console.log(result); // apple, banana, orange

split()

split() 메서드를 사용하여 문자열을 배열로 변환할 수 있다.

const fruits = '🍎, 🥝, 🍌, 🍒';
const result = fruits.split(', ');
console.log(result); // ['🍎', '🥝', '🍌', '🍒']

reverse()

reverse() 메서드를 사용하여 배열의 순서를 뒤집을 수 있다.

const array = [1, 2, 3, 4, 5];
const result = array.reverse();
console.log(result); // [5, 4, 3, 2, 1]
console.log(array); // [5, 4, 3, 2, 1] (원본 배열도 변경됨)

slice()

slice() 메서드를 사용하여 배열의 일부분을 새 배열로 만들 수 있다.

const array = [1, 2, 3, 4, 5];
const result = array.slice(2);
console.log(result); // [3, 4, 5]
console.log(array); // [1, 2, 3, 4, 5] (원본 배열은 변경되지 않음)

find()

find() 메서드를 사용하여 특정 조건을 만족하는 첫 번째 요소를 찾을 수 있다.

class Student {
  constructor(name, age, enrolled, score) {
    this.name = name;
    this.age = age;
    this.enrolled = enrolled;
    this.score = score;
  }
}
const students = [
  new Student('A', 29, true, 45),
  new Student('B', 28, false, 80),
  new Student('C', 30, true, 90),
  new Student('D', 40, false, 66),
  new Student('E', 18, true, 88),
];

const result = students.find((student) => student.score === 90);
console.log(result); // Student { name: 'C', age: 30, enrolled: true, score: 90 }

filter()

filter() 메서드를 사용하여 특정 조건을 만족하는 요소들만 모아 새로운 배열을 만들 수 있다.

const result = students.filter((student) => student.enrolled);
console.log(result); // [Student 객체들...]

map()

map() 메서드를 사용하여 각 요소에 대한 새 값을 가진 배열을 만들 수 있다.

const result = students.map((student) => student.score);
console.log(result); // [45, 80, 90, 66, 88]

some(), every

some()은 주어진 함수의 조건을 만족하는 요소가 하나라도 있으면 true를 반환하고, every()는 모든 요소가 조건을 만족해야 true를 반환한다.

const result = students.some((student) => student.score < 50);
console.log(result); // true 또는 false

const result2 = !students.every((student) => student.score >= 50);
console.log(result2); // true 또는 false

reduce()

reduce() 메서드를 사용하여 배열의 모든 요소를 순회하며 값을 누적할 수 있다.

const result = students.reduce((prev, curr) => prev + curr.score, 0);
console.log(result / students.length); // 평균 점수

활용 예시

학생의 점수를 문자열로 만드는 예
map()join()을 결합하여 모든 점수를 하나의 문자열로 합칠 수 있다.

const result = students
  .map((student) => student.score)
  .filter((score) => score >= 50)
  .join();
console.log(result); // '45, 80, 90, 66, 88'

오름차순으로 점수 정렬하기
sort() 메서드를 사용하여 점수를 오름차순으로 정렬할 수 있다.

const result = students
  .map((student) => student.score)
  .sort((a, b) => a - b)
  .join();
console.log(result); // '45, 66, 80, 88, 90'

0개의 댓글