Javascript-reduce

Javascript-reduce

JS의 reduce 메서드는 빈 원소를 제외하고 배열 내의 모든 원소에 callback 함수를 실행하는 메서드입니다.

말만 듣고는 잘 이해가 안가는데요.

배열의 모든 원소를 합치는 예시를 보겠습니다.

var sum = [0, 1, 2, 3].reduce(function (accumulator, currentValue) { return accumulator + currentValue; }, 0);

reduce안에 accumulator와 currentValue 를 합치는 function이 있고, 그 function이 [0, 1, 2, 3]을 돌면서 모든 원소에 작동하므로 원소의 모든 합인 6을 반환합니다.

accumulator와 currentValue 말고도 다른 input이 있습니다.

callback accumulator 콜백 함수의 누적합입니다. initialValue가 있는 경우 처음에는 initialValue 값을 가집니다. currentValue currentIndex (Optional) 현재 요소의 인덱스입니다. initialValue가 있는 경우 처음에는 0, 없는 경우는 1을 가집니다. array (Optional)

initialValue (Optional) 콜백 최초에 첫 번째 인수에 제공하는 값입니다. 간단하게 생각하면 배열의 0번째에 initialValue를 넣고 reduce를 실행한다 생각해도 됩니다. 없는 경우에는 배열의 첫 번째 요소를 사용합니다.

같은 배열에 initialValue가 있고 없고의 차이는 다음 예시를 보면 이해가 쉽습니다.

const array1 = [1, 2, 3, 4]; const reducer = (previousValue, currentValue) => previousValue + currentValue; // 1 + 2 + 3 + 4 console.log(array1.reduce(reducer)); // expected output: 10 // 5 + 1 + 2 + 3 + 4 console.log(array1.reduce(reducer, 5)); // expected output: 15

일반적인 reduce의 작동방식을 나타낸 설명은 아래와 같습니다.

아래는 모두 사용 예시십니다.

배열 원소의 합 var sum = [0, 1, 2, 3].reduce(function (accumulator, currentValue) { return accumulator + currentValue; }, 0); // sum is 6 var total = [ 0, 1, 2, 3 ].reduce( ( accumulator, currentValue ) => accumulator + currentValue, 0 ); // sum is 6 var initialValue = 0; var sum = [{x: 1}, {x:2}, {x:3}].reduce(function (accumulator, currentValue) { return accumulator + currentValue.x; },initialValue) console.log(sum) // logs 6 var initialValue = 0; var sum = [{x: 1}, {x:2}, {x:3}].reduce( (accumulator, currentValue) => accumulator + currentValue.x ,initialValue ); console.log(sum) // logs 6​

배열 합치기 var flattened = [[0, 1], [2, 3], [4, 5]].reduce( function(accumulator, currentValue) { return accumulator.concat(currentValue); }, [] ); var flattened = [[0, 1], [2, 3], [4, 5]].reduce( ( accumulator, currentValue ) => accumulator.concat(currentValue), [] ); // 펼친 결과: [0, 1, 2, 3, 4, 5]​

배열 원소 세기

var names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice']; var countedNames = names.reduce(function (allNames, name) { if (name in allNames) { allNames[name]++; } else { allNames[name] = 1; } return allNames; }, {}); // countedNames is: // { 'Alice': 2, 'Bob': 1, 'Tiff': 1, 'Bruce': 1 }

출처 : https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

from http://developerlee.tistory.com/19 by ccl(A) rewrite - 2021-11-09 03:28:16