✨직접 작성한 reducer function을 주입하여, 배열(array)의 여러 값을 하나씩 다루고, 최종적으로 single value를 도출해낸다.
(e.g., arr.reduce((acc, val) => acc += val)) 왼쪽처럼 기본적으로 첫 번째 argument는 accumulator, 두 번째 argument는 Current Value이며, 그 외에 세 번째 argument는 Current Index이며, reduce()의 두 번째 arugument에 initialValue(초기값)을 작성하여 acc에 초기값을 지정하는 것도 가능하다.
Reverse Int(or String)와 palindrome(회문 구조) 등 다양한 로직에서 유용하다.
💻Example Code
const numArr = [ 1, 2, 3, 4 ];
const strArr = [ 'b', 'c', 'd', 'e' ];
console.log(numArr.reduce((acc, num) => (acc = num + acc), 10));
console.log(strArr.reduce((rev, char) => (rev = char + rev), 'a'));
😋 배열의 모든 값을 간단하게 더하고 싶을 때, 배열의 문자를 거꾸로 정렬하고 싶을 때 등 다양한 기능에서 활용이 가능하다.
👉 자세한 내용은 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
'JavaScript > Built-in Method etc.' 카테고리의 다른 글
Array.prototype.includes() (0) | 2019.12.26 |
---|---|
Array.prototype.every() (0) | 2019.12.24 |
Array.prototype.join() (0) | 2019.12.24 |
Array.prototype.reverse() (0) | 2019.12.24 |
Number.prototype.toString() (0) | 2019.12.24 |