Array.prototype.reduce()

2023. 4. 20. 14:29·NOTE

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

'NOTE' 카테고리의 다른 글

HTTP, HTTPS의 차이  (0) 2023.04.20
[용어] 인스턴스와 프로퍼티, 메소드  (0) 2023.04.20
node.js, npm, npx  (0) 2023.04.19
함수와 메소드 차이  (0) 2023.04.19
call, bind, apply의 this binding  (0) 2023.04.19
'NOTE' 카테고리의 다른 글
  • HTTP, HTTPS의 차이
  • [용어] 인스턴스와 프로퍼티, 메소드
  • node.js, npm, npx
  • 함수와 메소드 차이
ssund
ssund
  • ssund
    ssund의 기술블로그
    ssund
  • 전체
    오늘
    어제
    • 분류 전체보기 (74)
      • TECH (23)
      • NOTE (40)
      • DAILY (7)
      • javascript (1)
      • 알고리즘 (0)
  • 블로그 메뉴

    • 홈
    • TECH
    • NOTE
    • DAILY
  • 링크

  • 공지사항

  • 인기 글

  • 태그

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

  • 최근 글

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

티스토리툴바