본문 바로가기
기초다지기/Javascript

javaScript reduce 알아보기

by 김빵그 2023. 11. 1.

 Array.prototype.reduce()

  • reduce()메서드는 배열의 각 요소에 대해 주어진 리듀서 (reducer) 함수를 실행하고, 하나의 결과값을 반환한다

기초 구문

  arr.reduce(callback[, initialValue])
  • callback : 배열의 각 요소에 대해 실행할 함수
    • accumulator (누산기) : 콜백의 반환값을 누적한다. 콜백의 이전 반환값 또는 콜백의 첫번 째 호출이면서 initialValue를 제공한 경우 initialValue의 값이다
    • currentValue (현재 값) : 처리할 현재 요소
    • currentIndex (인덱스) : 처리할 현재 요소의 인덱스 initialValue를 제공한 경우 0, 아니면 1부터 시작한다
  • initialValue ; callback의 최초 호출에서 첫 번째 인수에 제공하는 값, 초기값을 제공하지 않으면 배열의 첫번째 요소를 사용한다. 빈 배열에서 초기값 없이 reduce() 를 호출하면 오류가 발생

 

예제

1). 배열 요소 합

const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
console.log(sum); // 출력: 15

2) 배열 요소 곱 

const numbers = [1, 2, 3, 4, 5];
const product = numbers.reduce((accumulator, currentValue) => accumulator * currentValue, 1);
console.log(product); // 출력: 120

3) 최대값 찾기

const numbers = [12, 6, 34, 78, 45];
const max = numbers.reduce((accumulator, currentValue) => Math.max(accumulator, currentValue), -Infinity);
console.log(max); // 출력: 78

4) 최소값 찾기

const numbers = [12, 6, 34, 78, 45];
const min = numbers.reduce((accumulator, currentValue) => Math.min(accumulator, currentValue), Infinity);
console.log(min); // 출력: 6

5) 객체속성합산하기

const data = [{ value: 10 }, { value: 20 }, { value: 30 }];
const total = data.reduce((accumulator, currentValue) => accumulator + currentValue.value, 0);
console.log(total); // 출력: 60

6) 배열 요소 문자열 결합

const words = ['Hello', 'world', 'this', 'is', 'OpenAI'];
const sentence = words.reduce((accumulator, currentValue) => accumulator + ' ' + currentValue);
console.log(sentence); // 출력: "Hello world this is OpenAI"

7) 중복요소 제거

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]

 

 

Array.prototype.reduce() - JavaScript | MDN

reduce() 메서드는 배열의 각 요소에 대해 주어진 리듀서 (reducer) 함수를 실행하고, 하나의 결과값을 반환합니다.

developer.mozilla.org