Changetodev's Blog

JavaScript 기본기 다지기(3) - reduce

Created Date
May 7, 2025
group
이론
state
진행 중
Tags
JavaScript
Thumbnail
images.jpg
코딩 테스트를 준비하다 보면 반복적으로 언급되는 녀석들이 있다.
오늘은 그중에서 reduce를 알아보도록 하자( useReducer 보다 나중에 배우는게 웃기긴함)
 

1. reduce() 함수는 뭐고 언제 쓰는 걸까?

 

reduce() 함수 정의

배열의 모든 요소를 하나의 값으로 줄여나가는 함수형 메서드. 합계, 객체 누적, 카운트, 중첩된 데이터 가공에 사용된다.
역시 CS지식은 오늘도 어김없이 한번에 못 알아 듣겠다.
 

📌 기본 문법

/* accumulator : 누적된 결과값 * currentValue : 현재 훈회 중인 요소 * index : 순회중인 요소의 인덱스 * array : 대상의 전체 배열요소(즉 array) * initialValue :accumulator의 초기값(초기 값이 없다면 배열의 첫번째 요소로 시작) */ array.reduce((accumulator, currentValue, index, array)=>{ return newAccumulator; }, initialValue);
 

2.reduce()의 사용 예시

예제. 중복 빈도를 따지고 제일 많이 나온 아이탬 찾기

 
문제.
문자열 배열 `fruits`가 주어진다. 각 과일이 몇 번씩 등장했는지를 객체로 만들고, 그중 가장 많이 등장한 과일 이름을 return 해보자.
 
해결.
const fruits = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']; const count = fruits.reduce((acc, current)=>{ acc[current] = (acc[current]||0)+1 return acc; },{}) const keys = Object.keys(count); let answer=""; let pre = 0; for(const key of keys){ let now = count[key] if(now>pre){ pre = now; answer = key; } }
 
번외.
객체를 탐색하며 최대 값만 남길 때도 reduce가 사용 가능하다.
const fruits = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']; const count = fruits.reduce((acc, current)=>{ acc[current] = (acc[current]||0)+1 return acc; },{}) const result = Object.entries(count).reduce((acc,[key,value])=>{ return (value>acc[1]?[key,value]:acc) },["",0])[0]; console.log(result)
 
Object.entries는 Map에 있는 함수와 마찬가지로
키, 값을 묶어 순회 가능한 배열로 나타내는 함수
//객채를 키,값을 묶어 하나의 배열로 순차적으로 나열(이터러블) console.log(Object.entries(count)); Object.entries(count).forEach(([key,value])=>{ console.log(`key is ${key} | value is ${value}`) }) for (const [k,v] of Object.entries(count)){ console.log(`k is ${k} | v is ${v}`) }
notion image

2025.06.30
블로그 만들기 실전에서 reduce를 사용해보았다.
  • 태그 리스트의 집계를 사이드 네비게이션에 나타내야한다.
  • 이름이 긴 태그들은 축약을 해야 한다.
  • 축약된 데이터를 포함하여 이름이 짧은 순으로 정렬.
 
데이터는 notion Api의 결과로 받은 각 페이지의 정보 오브젝트의 배열이다.
각 오브젝트에는 tags 맴버가 있고 tags는 배열로 태그들을 가지고 있다.
//오브젝트의 예시 [ { pageId : pageIdString, tags : ['react','FSD','TanStackQuery','Frone-End'] }, {...} ]
 
구현 예시
export default function accumulateTag(totalResult:PostList){ //reducer로 오브젝트가 있는 배열을 순회. const tagCount = totalResult.reduce((acc,current)=>{ //해당 오브젝트안에 배열을 다시 순회하고 축약시키며 acc에 추가. current.tags.forEach((item)=>{ const tmepTag = tagNameReducing(item); acc[tmepTag] = (acc[tmepTag]||0)+1; }) return acc; },{} as Record<string, number>); //생성된 결과 값을 오름차순으로 정렬 const sortedTagCount = Object.entries(tagCount) .sort((a, b) => a[0].length - b[0].length) .reduce((acc, [key, value]) => { acc[key] = value; return acc; }, {} as Record<string, number>); return sortedTagCount; } function tagNameReducing(target:string){ switch(target){ case 'Front-end': return'FE'; case 'JavaScript': return 'JS' case 'TypeScript': return 'TS' default: return target; } }