코딩 테스트를 준비하다 보면 반복적으로 언급되는 녀석들이 있다.
오늘은 그중에서 reduce를 알아보도록 하자( useReducer 보다 나중에 배우는게 웃기긴함)
1. reduce() 함수는 뭐고 언제 쓰는걸까?
✅ reduce()
함수 정의
배열의 모든 요소를 하나의 값으로 줄여나가는 함수형 메서드. 합계, 객체 누적, 카운트, 중첩된 데이터 가공에 사용된다.
📌 기본 문법
/* accumulator : 누적된 결과값 * currentValue : 현재 훈회 중인 요소 * index : 순회중인 요소의 인덱스 * array : 대상의 전체 배열요소(즉 array) * initialValue :accumulator의 초기값(초기 값이 없다면 배열의 첫번째 요소로 시작) */ array.reduce((accumulator, currentValue, index, array)=>{ return newAccumulator; }, initialValue);
예제. 중복 빈도를 따지고 제일 많이 나온 아이탬 찾기
문제.
문자열 배열 `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}`) }
