ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • reduce() 메서드
    코드 찌끄리기 2024. 8. 8. 15:44

    reduce

    reduce 메서드는 JavaScript에서 배열의 각 요소를 순회하면서 특정한 방식으로 누적 결과를 계산하는 데 사용된다. reduce 메서드는 두 개의 인자를 받는 콜백 함수를 요구한다. 누적값(accumulator)과 현재값(current value)

     

    배열의 모든 숫자의 합을 구하기

    const numbers = [1, 2, 3, 4, 5];
    
    // 누적값(accumulator)과 현재값(current value)을 사용하여 합을 구함
    const sum = numbers.reduce((accumulator, currentValue) => {
      return accumulator + currentValue;
    }, 0); // 초기값 0
    
    console.log(sum); // 15

     

    배열의 요소를 문자열로 연결하기

    const words = ['Hello', 'world', 'from', 'reduce'];
    
    // 누적값(accumulator)과 현재값(current value)을 사용하여 문자열을 연결함
    const sentence = words.reduce((accumulator, currentValue) => {
      return accumulator + ' ' + currentValue;
    });
    
    console.log(sentence); // "Hello world from reduce"

     

     

    배열의 각 요소를 객체로 변환하기

    const people = ['Alice', 'Bob', 'Charlie'];
    
    // 배열의 각 요소를 객체로 변환하여 새로운 객체를 생성함
    const peopleObject = people.reduce((accumulator, currentValue) => {
      accumulator[currentValue] = currentValue.length; // 이름을 키로 하고 이름 길이를 값으로 저장
      return accumulator;
    }, {});
    
    console.log(peopleObject);
    // { Alice: 5, Bob: 3, Charlie: 7 }

     

    중첩된 배열을 평탄화하기

    const nestedArrays = [[1, 2], [3, 4], [5, 6]];
    
    // 중첩된 배열을 하나의 배열로 평탄화함
    const flattened = nestedArrays.reduce((accumulator, currentValue) => {
      return accumulator.concat(currentValue);
    }, []);
    
    console.log(flattened); // [1, 2, 3, 4, 5, 6]

     

    객체의 배열에서 특정 속성의 합계를 계산하기

    const orders = [
      { item: 'Apple', quantity: 4 },
      { item: 'Banana', quantity: 6 },
      { item: 'Cherry', quantity: 3 }
    ];
    
    // 모든 주문의 총 수량을 계산함
    const totalQuantity = orders.reduce((accumulator, order) => {
      return accumulator + order.quantity;
    }, 0);
    
    console.log(totalQuantity); // 13

     

    배열에서 가장 큰 값 찾기

    const numbers = [10, 5, 100, 50, 75];
    
    // 배열에서 가장 큰 값을 찾음
    const maxNumber = numbers.reduce((max, currentValue) => {
      return currentValue > max ? currentValue : max;
    }, numbers[0]); // 초기값으로 배열의 첫 번째 요소를 사용
    
    console.log(maxNumber); // 100

     

    배열의 중복된 값 제거하기

    const numbers = [1, 2, 2, 3, 4, 4, 5];
    
    // 중복된 값을 제거하여 유니크한 배열을 생성함
    const uniqueNumbers = numbers.reduce((accumulator, currentValue) => {
      if (!accumulator.includes(currentValue)) {
        accumulator.push(currentValue);
      }
      return accumulator;
    }, []);
    
    console.log(uniqueNumbers); // [1, 2, 3, 4, 5]

     

    reduce 메서드는 다양한 방식으로 배열을 처리할 수 있는 강력한 도구이므로, 배열을 순회하면서 데이터를 집계하거나 변환할 때 매우 유용하다.

    '코드 찌끄리기' 카테고리의 다른 글

    타입스크립트 공부하기  (0) 2024.09.22
    Context API  (1) 2024.08.09
    splice() 메서드  (0) 2024.08.08
    slice() 메서드  (3) 2024.08.08
    filter() 메서드  (0) 2024.08.07
Designed by Tistory.