Array.prototype.reduce()

2023. 4. 20. 14:29·javascript

reduce라고 하면 떠올리는 것 ! 누산기

누산이란 ? 소계(小計)를 계속하여 덧붙여 합산함. 또는 그런 합계를 말한다.

 

배열의 모든 원소에 대해 특정한 연산을 순차적으로 적용할 때 사용한다. 

배열의 원소 합을 구하거나, 배열의 길이, 원소의 최대값을 구할 수있다. 

reduce(callbackFn) //initialValue를 생략할수도 있다.
reduce(callbackFn, initialValue)

 

배열의 원소들의 전체 합 구하기

reduce callback 함수안에 accumulator가 계산된 이전값,
currentValue는 현재 인덱스에 해당하는 배열원소의 값이 된다.

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

// 0 + 1 + 2 + 3 + 4
const initialValue = 0;
const sumWithInitial = array1.reduce(
  (accumulator, currentValue) => (accumulator + currentValue),
  initialValue
);

console.log(sumWithInitial);
// Expected output: 10

 

오브젝트가 요소로 있는 배열의 특정값도 합산할 수 있다. 

const testArr = [{value: 1}, {value : 2}, {value: 3}, {value: 4}];
testArr.reduce((acc, curr) => acc + curr.value, 0) //10

 

배열의 원소의 최대값 구하기

Math.max 메소드를 이용하여 이전값과 현재인텍스 요소값을 비교하여 최대값을 구할 수 있다.

const array1 = [1, 10, 3, 4, 9, 99];

const sumWithInitial = array1.reduce(
  (accumulator, currentValue) => Math.max(accumulator, currentValue)
);

console.log(sumWithInitial); //99

 

배열의 최대값은 reduce를 이용하지 않고 Math.max 메소드를 이용해서 간단하게 구할수 있다. 

const testArr = [1, 2, 3, 5, 99, 9];

console.log(Math.max(testArr)); // NaN
console.log(Math.max(...testArr)); // 99

 

배열 합치기 

배열에 요소로 들어가있는 배열을 합쳐서 하나의 배열로 리턴할 수 있다. 

각각의 요소를 돌며 배열요소를 concat을 이용하여 acc 배열에 합친다. 

const testArray = [[1, 2], [3, 4], [5, 6]];
const reducedArray = testArray.reduce((acc, curr) => acc.concat(curr));

console.log(reducedArray); // [1, 2, 3, 4, 5, 6]

 

딕셔너리 만들기

빈 객체를 초기값으로 정해준다.

const stringArr = ['aa', 'bb'];

const dictionary = stringArr.reduce((acc, curr) => {
    acc[curr] = curr
    return acc;
}, {});

console.log(dictionary);

 

딕셔너리를 만들고 동일한 요소가 몇개인지 카운트하는 로직

const testCountedArr = ['A', 'B', 'A', 'A', 'B'];

testCountedArr.reduce((acc, curr) => {
    if(curr in acc) {
        // 만약 배열에 해당 요소가 있으면 숫자 올린다.
        acc[curr]++
    } else {
        // 배열에 해당 요소가 없으면 default value = 1을 준다.
        acc[curr] = 1
    }

    return acc;
}, {});

 

 

 

 

 

참고

https://m.blog.naver.com/wideeyed/221877924629

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

'javascript' 카테고리의 다른 글

String.charAt(index)  (0) 2023.05.05
배열의 두 요소 순서를 변경할 때  (0) 2023.05.05
call, bind, apply의 this binding  (0) 2023.04.19
자바스크립트 sort()로직  (0) 2023.04.15
fetch() error 처리하기  (0) 2023.03.17
'javascript' 카테고리의 다른 글
  • String.charAt(index)
  • 배열의 두 요소 순서를 변경할 때
  • call, bind, apply의 this binding
  • 자바스크립트 sort()로직
ssund
ssund
  • ssund
    ssund의 기술블로그
    ssund
  • 전체
    오늘
    어제
    • TECH (82)
      • Next.js (8)
      • React (25)
      • Vite (1)
      • javascript (17)
      • CSS (6)
      • CS (10)
      • AWS (0)
      • Jest (1)
      • CI|CD (0)
      • 알고리즘 (8)
      • Tools (1)
      • Tips (5)
  • 블로그 메뉴

    • 링크

    • 공지사항

    • 인기 글

    • 태그

      배열요소순서
      커머스프로젝트
      redux
      React
      서버컴포넌트
      Array.sort()
      함수와 메서드차이
      reat-head
      global-style
      styled-components
      타입스크립트
      call signatures
      JavaScript
      웹브라우저구성
      app-router
      nextjs
      react state management
      git배포
      theme-provider
      TypeScript
    • 최근 댓글

    • 최근 글

    • hELLO· Designed By정상우.v4.10.0
    ssund
    Array.prototype.reduce()
    상단으로

    티스토리툴바