본문 바로가기
Javascript

[JS] Reducer?

by F.E.D 2019. 1. 27.

[JS] Reducer?


1
2
3
4
5
6
7
8
9
10
11
// 일반 예제
const nums = [123]
let value = 0
 
for (let i = 0; i < nums.length; i++) {
  value += nums[i]
}
 
// Reducer 사용
const nums = [123]
const value = nums.reduce((ac, next) => ac + next, 0)
cs

기능적으로 동등하며 배열의 모든 숫자를 합산합니다. 
그러나 약간의 패러다임이 있습니다. 

가장 중요한 기능 중 하나는 Reducer는 하나의 값만 반환한다는 것입니다. 하나의 값은 숫자, 문자열, 배열 또는 객체 일 수 있지만 항상 하나뿐입니다. Reducer는 값 그룹에 약간의 로직을 적용하고 또 다른 단일 결과로 끝내는 데 특히 유용합니다.


위 영상의 각 단계별로 변화는 다음과 같습니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// 1단계
const nums = [123]
const initialValue = 0
 
const reducer = function (acc, item) { 
  return acc + item
}
 
const total = nums.reduce(reducer, initialValue)
 
// 2단계 (화살표 함수)
const nums = [123]
const initialValue = 0
 
const reducer = (acc, item) => { 
  return acc + item
}
 
const total = nums.reduce(reducer, initialValue)
 
// 3단계 (괄호 제거)
const nums = [123]
const initialValue = 0
 
const reducer = (acc, item) => acc + item
 
const total = nums.reduce(reducer, initialValue)
 
// 4단계 (한줄로 함축)
const nums = [123]
 
const total = nums.reduce((acc, item) => acc + item,
cs

배열에 숫자가 있고 그 배열에 숫자가 나오는 횟수를보고하는 객체를 반환한다고 가정 해 보겠습니다. 
문자열에 쉽게 적용 할 수 있습니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
const nums = [35682143582]
 
 
const result = nums.reduce((tally, amt) => {
  tally[amt] ? tally[amt]++ : tally[amt] = 1
  return tally
}, {})
 
console.log(result)
 
 
 
 
const nums = [35682143582]
// 우리는 짝수와 홀수의 객체를 만들 예정입니다. 
const result = nums.reduce((acc, item) => {
  acc[item] = {
    odd: item % 2 ? item : item - 1,
    even: item % 2 ? item + 1 : item
  }
  return acc
}, {})
 
console.log(result)
 
 
// 콘솔 
1:{odd: 1, even: 2}
3:{odd: 3, even: 4}
4:{odd: 3, even: 4}
5:{odd: 5, even: 6}
6:{odd: 5, even: 6}
82:{odd: 81, even: 82}
cs


출처 : https://css-tricks.com/understanding-the-almighty-reducer/


'Javascript' 카테고리의 다른 글

Javascript 함수가 왜 1급 객체일까?  (0) 2019.09.12
[JS] JS 5가지 팁  (0) 2019.02.01
[JS] IOS의 CLICK 버블링이 발생하지 않아요  (0) 2019.01.27
[JS] GITHUB이 Jquery를 삭제하다  (0) 2019.01.26
[JS] Map vs ForEach  (2) 2018.08.25

댓글