# 01. reduce
reduce 함수는 빈 요소를 제외하고 배열 내에 존재하는 각 요소에 대해 배정된 콜백함수를 한번씩 실행한다.
이 콜백함수는 아래 4개의 인자를 받는다.
1) 누산기 (acc)
2) 현재값 (cur)
3) 현재 인덱스 (idx)
4) 원본배열 (src)
그리고 initialValue값을 가진다.
구문)
arr.reduce(callback[, initialValue])
# 02. 예시
1) 합산하기
const array1 = [1, 2, 3, 4];
// 0 + 1 + 2 + 3 + 4
const initialValue = 0;
const sumWithInitial = array1.reduce(
(previousValue, currentValue) => previousValue + currentValue,
initialValue
);
console.log(sumWithInitial);
// expected output: 10
2) 평균값 구하기
students란 학생정보가 담긴 배열이 있고, 60점이 넘는 학생들만 추려 평균값을 내는 코드가 있다.
먼저 filter를 통해 60점이 넘는 학생만 새로 배열을 만들고 이어서 reduce를 사용하는데
acc, cur, idx, src 인자 중 사용하지 않는 idx는 ' _ '로 변경할 수 있음
const students = [
{
name: 'John',
score: 50,
},
{
name: 'Mary',
score: 100,
},
{
name: 'Peter',
score: 90,
},
{
name: 'Jane',
score: 60,
},
{
name: 'Anne',
score: 80,
}
]
const avg = students
.filter((student)=>student.score>60)
.reduce( (acc,cur,_,src)=> acc+cur.score/src.length,0);
console.log(avg) //90
'공부 > JavaScript' 카테고리의 다른 글
구조분해할당 (0) | 2022.12.21 |
---|---|
논리 연산자 (Logical Operator) (0) | 2022.12.15 |
Class - this 바인딩 (0) | 2022.11.04 |
Truthy & Falsy (0) | 2022.09.12 |
async, await (0) | 2022.09.01 |