반응형
Notice
Recent Posts
Recent Comments
Link
taenyLog
[JavaScript] Reduce 본문
반응형
Reduce
Executes a reducer function on each element of the array, resulting in a single value.
배열을 가져다가 점차 줄여가면서 마지막에는 결국 하나의 값만 남긴다.
배열이름.reduce((accumulator,elememt) =>{
return accumulator + elememt
})
최댓값, 최솟값 찾기도 가능하다.
ex) 가장 높은 / 낮은 평점을 받은 영화를 찾기
초기값 없이 reduce()
const array = [15, 16, 17, 18, 19];
function reducer(accumulator, currentValue, index) {
const returns = accumulator + currentValue;
console.log(
`accumulator: ${accumulator}, currentValue: ${currentValue}, index: ${index}, returns: ${returns}`,
);
return returns;
}
array.reduce(reducer);
콜백은 4번 호출
First call | 15 | 16 | 1 | 31 |
Second call | 31 | 17 | 2 | 48 |
Third call | 48 | 18 | 3 | 66 |
Fourth call | 66 | 19 | 4 | 85 |
초기값과 reduce()
[15, 16, 17, 18, 19].reduce(
(accumulator, currentValue) => accumulator + currentValue,
10,
);
콜백은 5번 호출
First call | 10 | 15 | 0 | 25 |
Second call | 25 | 16 | 1 | 41 |
Third call | 41 | 17 | 2 | 58 |
Fourth call | 58 | 18 | 3 | 76 |
Fifth call | 76 | 19 | 4 | 95 |
위의 코드에서 10을 초기값으로 넣어줬기때문에 First call이 10으로 시작하는 것을 볼 수 있다.
반응형
'Web' 카테고리의 다른 글
[JavaScript] Default Params(old way VS new way) (0) | 2023.09.26 |
---|---|
[JavaScript] Arrow Function and 'this' (0) | 2023.09.26 |
[JavaScript] some / every exercise (0) | 2023.09.26 |
[JavaScript] some and every method (0) | 2023.09.23 |
[JavaScript] JavaScript와 HTML 연결하기. (0) | 2023.09.22 |