Javascript

[JavaScript] 자바스크립트 | 유용한 10가지 배열 함수들 | Array APIs 정리

@leem 2025. 3. 19. 22:54
이 글은 드림코딩 유튜브 강의를 보며 학습한 내용을 정리한 JavaScript 복습 노트입니다.
// Q1. make a string out of an array (배열을 문자열로 변환)
{
  const fruits = ['apple', 'banana', 'orange'];
  
  // join(separator): 배열의 요소를 하나의 문자열로 합침. separator로 구분자를 지정할 수 있음.
  const result = fruits.join(','); // 요소들을 ','로 구분하여 문자열로 변환
  console.log(result); // "apple,banana,orange"
}

// Q2. make an array out of a string (문자열을 배열로 변환)
{
  const fruits = '🍎, 🥝, 🍌, 🍒';
  
  // split(separator): 문자열을 separator(구분자) 기준으로 나누어 배열로 변환.
  const result = fruits.split(','); // ','를 기준으로 문자열을 나눠 배열로 만듦
  console.log(result); // ['🍎', ' 🥝', ' 🍌', ' 🍒']
}

// Q3. make this array look like this: [5, 4, 3, 2, 1] (배열 순서 뒤집기)
{
  const array = [1, 2, 3, 4, 5];

  // reverse(): 배열의 요소 순서를 거꾸로 변경 (원본 배열도 변경됨)
  const result = array.reverse();
  console.log(result); // [5, 4, 3, 2, 1]
  console.log(array); // 원본 배열도 변경됨 → [5, 4, 3, 2, 1]
}

// Q4. make new array without the first two elements (배열의 처음 두 개 요소 제거)
{
  const array = [1, 2, 3, 4, 5];

  // slice(start, end): start 인덱스부터 end 인덱스 전까지의 새로운 배열을 반환 (원본 배열은 변경되지 않음)
  const result = array.slice(2, 5); // 인덱스 2부터 4까지의 요소를 새로운 배열로 반환
  console.log(result); // [3, 4, 5]
  console.log(array); // 원본 배열 유지됨 → [1, 2, 3, 4, 5]
}

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),
];

// Q5. find a student with the score 90 (점수가 90인 학생 찾기)
{
  // find(callback): 조건에 맞는 첫 번째 요소를 반환 (못 찾으면 undefined 반환)
  const result = students.find((student) => student.score === 90);
  console.log(result); // Student { name: 'C', age: 30, enrolled: true, score: 90 }
}

// Q6. make an array of enrolled students (등록된 학생만 추출)
{
  // filter(callback): 조건을 만족하는 요소들만 배열로 반환
  const result = students.filter((student) => student.enrolled);
  console.log(result); // 등록된 학생들만 출력
}

// Q7. make an array containing only the students' scores (학생 점수만 배열로 만들기)
{
  // map(callback): 각 요소를 변환하여 새로운 배열 생성
  const result = students.map((student) => student.score);
  ㅊ // [45, 80, 90, 66, 88]
}

// Q8. check if there is a student with the score lower than 50 (점수가 50점 미만인 학생이 있는지 확인)
{
  console.clear();

  // some(callback): 배열 내 요소 중 하나라도 조건을 만족하면 true 반환
  const result = students.some((student) => student.score < 50);
  console.log(result); // true (점수 45인 학생이 있음)

  // every(callback): 배열 내 모든 요소가 조건을 만족하면 true, 하나라도 안 맞으면 false
  const result2 = !students.every((student) => student.score >= 50);
  console.log(result2); // true (50점 미만이 있음)
}

console.clear();

// Q9. compute students' average score (학생 평균 점수 계산)
{
  // reduce((누적값, 현재값) => 계산식, 초기값): 배열을 하나의 값으로 축소
  const totalScore = students.reduce((prev, curr) => prev + curr.score, 0);
  console.log(totalScore / students.length); // 평균 계산
}

// Q10. make a string containing all the scores (학생 점수를 문자열로 변환)
{
  const result = students
    .map((student) => student.score) // 점수만 배열로 변환
    .filter((score) => score >= 50) // 50점 이상만 필터링
    .join(); // 배열을 문자열로 변환
  console.log(result); // "80,90,66,88"
}

// Bonus! do Q10 sorted in ascending order (점수를 오름차순 정렬 후 문자열로 변환)
{
  const result = students
    .map((student) => student.score) // 점수만 배열로 변환
    .sort((a, b) => a - b) // 오름차순 정렬
    .join(); // 문자열로 변환
  console.log(result); // "45, 66, 80, 88, 90"
}

✅ 배열 변환 메서드

  • join(separator): 배열을 하나의 문자열로 변환, 구분자 지정 가능.
  • split(separator): 문자열을 구분자로 나누어 배열로 변환.
  • reverse(): 배열을 반대로 뒤집음. (원본 배열 변경됨)
  • slice(start, end): 일부 요소를 추출하여 새로운 배열 생성 (원본 배열 유지됨).

✅ 배열 검색 및 필터링

  • find(callback): 조건에 맞는 첫 번째 요소 반환 (없으면 undefined).
  • filter(callback): 조건을 만족하는 모든 요소를 배열로 반환.
  • map(callback): 각 요소를 변환하여 새로운 배열 생성.
  • some(callback): 하나라도 조건을 만족하면 true.
  • every(callback): 모든 요소가 조건을 만족하면 true.

✅ 배열 연산

  • reduce((acc, curr) => acc + curr, 초기값): 배열을 누적 연산하여 단일 값으로 축소.
  • sort((a, b) => a - b): 오름차순 정렬.
  • join(): 배열을 문자열로 변환, 요소 사이 구분자 설정 가능.