Array.reduce
reduce 함수는 배열의 요소들을 하나씩 돌면서, 이전 콜백의 리턴 값을 넘겨받아 작업을 수행하는 메서드
arr.reduce( callback( 콜백함수 리턴값, 배열요소의 값, 배열요소의 index ), 콜백함수 리턴값의 초기 값)
reduce의 가장 기본형 (가장 기본적으로 배열의 합을 구하는 코드)
let sum = [1, 2, 3, 4, 5]
var a = sum.reduce(function (tot, el, i) {
return tot + el
}, 0)
// a = 15
// sum = [1, 2, 3, 4, 5]
// 1번째 tot = 0, el = 1, i = 0, return 1
// 2번째 tot = 1, el = 2, i = 1, return 3
// 3번째 tot = 3, el = 3, i = 2, return 6
// 4번째 tot = 6, el = 4, i = 3, return 5
// 5번째 tot = 10, el = 5, i = 4, return 15
//arrow function
let sum = [1, 2, 3, 4, 5]
var a = sum.reduce(
( tot, el ) => tot + el,
0
)
활용 방법
// concat을 사용하여 하나의 배열로 만든다.
let flattened = [[0, 1], [2, 3], [4, 5]].reduce(
( accumulator, currentValue ) => accumulator.concat(currentValue),
[]
)
// [0, 1, 2, 3, 4, 5]
concat을 활용하여 여러개의 배열을 하나의 배열로 만든다.
let myArray = ['a', 'b', 'a', 'b', 'c', 'e', 'e', 'c', 'd', 'd', 'd', 'd']
let myOrderedArray = myArray.reduce(function (accumulator, currentValue) {
if (accumulator.indexOf(currentValue) === -1) {
accumulator.push(currentValue)
}
return accumulator
}, [])
//[ 'a', 'b', 'c', 'e', 'd' ]
indexOf를 사용하여 중복된 원소를 제거할 수 있다.
[출처 및 참고]
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
'공부 ✍' 카테고리의 다른 글
전위연산자와 후위연산자 (0) | 2022.10.14 |
---|---|
[스타트업] IR? EXIT? (0) | 2022.10.09 |
반응형 모바일 우선 개발 방법 (2) | 2022.09.30 |
CSS 속성 순서 (2) | 2022.09.30 |
쿠키(cookie)와 세션(session) (0) | 2022.09.13 |