[JS] 배열 메서드 reduce

Subin Ryu·2024년 11월 21일
post-thumbnail

배열 메서드 reduce

  1. 개념
  2. 기본 문법
  3. 기본 사용 예제
  4. 응용 예제

개념

  • 배열의 각 요소를 순회하며 누적 작업을 수행하거나 변환할 때 사용하는 강력한 메서드
  • 초기값 설정에 따라 다양한 로직을 유연하게 구현할 수 있음.
  • reduce는 기존 배열을 변형하지 않고, 최종 값을 반환함.
  • 이 값은 숫자, 객체, 배열, 문자열 등 어떤 유형이든 가능.
  • 합계 계산, 배열 변환, 중첩 배열 평탄화, 객체 생성 등 다양한 작업에 활용됨.

기본 문법

array.reduce(callback, initialValue)
  • 매개변수:
    • callback: 배열의 각 요소에 대해 호출되는 함수. 다음의 인수를 가집니다:
      • accumulator: 이전 콜백 실행의 반환 값 또는 initialValue.
      • currentValue: 현재 처리 중인 배열의 요소.
      • currentIndex: 현재 요소의 인덱스 (선택적).
      • array: reduce를 호출한 원본 배열 (선택적).
    • initialValue: accumulator의 초기 값. 생략 시 배열의 첫 번째 요소가 초기 값으로 사용됨.
  • 반환값:
    • 콜백 함수의 최종 반환 값.

기본 사용 예제

배열의 합계 계산:

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

const sum = numbers.reduce((accumulator, currentValue) => {
  return accumulator + currentValue;
}, 0);

console.log(sum); // 15
  1. 초기 값 (0): accumulator는 처음에 0으로 설정됨.
  2. 배열을 순회하며 각 요소(currentValue)를 더함.
  • 실행 과정:
    • 첫 번째 반복: accumulator = 0, currentValue = 1 → 반환값: 1
    • 두 번째 반복: accumulator = 1, currentValue = 2 → 반환값: 3
    • ...
    • 마지막 반복: accumulator = 10, currentValue = 5 → 반환값: 15

초기 값을 생략한 경우

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

const sum = numbers.reduce((accumulator, currentValue) => {
  return accumulator + currentValue;
});

console.log(sum); // 15
  • 초기 값 생략 시:
    첫 번째 요소 (1)가 accumulator로 설정되고, 순회는 두 번째 요소부터 시작

응용 예제

  1. 중첩 배열 평탄화 (Flattening an array)
const nestedArray = [[1, 2], [3, 4], [5]];
const flatArray = nestedArray.reduce((acc, curr) => acc.concat(curr), []);

console.log(flatArray); // [1, 2, 3, 4, 5]
  1. 배열을 객체로 변환
const fruits = ["Apple", "Banana", "Apple", "Orange", "Banana"];
const fruitCount = fruits.reduce((acc, fruit) => {
  acc[fruit] = (acc[fruit] || 0) + 1; // 각 과일의 개수를 누적
  return acc;
}, {});

console.log(fruitCount);
// { Apple: 2, Banana: 2, Orange: 1 }
const fruits = ["Apple", "Banana", "Apple", "Orange", "Banana"];
const fruitCount = fruits.reduce((acc, fruit) => {
  acc[fruit] = (acc[fruit] || 0) + 1; // 각 과일의 개수를 누적
  return acc;
}, {});

console.log(fruitCount);
// { Apple: 2, Banana: 2, Orange: 1 }
  1. 비동기 작업 순차 처리
const urls = ["url1", "url2", "url3"];
const fetchUrlsSequentially = urls.reduce((promise, url) => {
  return promise
  .then(() => fetch(url))
  .then((res) => res.json())
  .then((data) => results.push(data));
}, Promise.resolve());

fetchUrlsSequentially.then(() => console.log("All done!"));
profile
개발블로그입니다.

0개의 댓글