구문
arr.reduce(callback[,initialValue])
콜백함수인
reducer 함수를 실행하고 그 결과값을 반환함.누산기라고 보면 됨.매개변수
1)
callback Required배열의 각 요소에 대해 실행할 함수. 다음 네 가지 인수를 받습니다.
accumulatorRequired 누산기. 콜백의 반환값을 누적한다. 콜백의 이전 반환값 또는, 콜백의 첫 번째 호출이면서initialValue를 제공한 경우에는initialValue의 값임.
currentValueRequired 처리할 현재 요소.
currentIndexOptional 처리할 현재 요소의 인덱스.initialValue를 제공한 경우 0, 아니면 1부터 시작.
arrayOptionalreduce()를 호출한 원본 배열.
2)
initialValue Optional 콜백함수의 첫번째 인수로 제공하는 값.초기 값을 제공하지 않으면 콜백함수 시작 시
*
acc : 배열의 0번째 요소
* cur : 배열의 1번째 요소
로 시작하고,
초기값을 제공하면
* acc : 초기값
* cur : 배열의 0번쨰 요소
로 시작한다.반환값
누적 계산의 최종 결과값을 반환.
코드 예시
배열값 합산
const array1 = [1, 2, 3, 4]; const reducer = (accumulator, currentValue) => accumulator + 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
오브젝트 배열의 값 합산
const initialValue = 0; const sum = [{x: 1}, {x:2}, {x:3}].reduce( (accumulator, currentValue) => accumulator + currentValue.x ,initialValue ); console.log(sum) // 6
중첩 배열 펼치기
const flattened = [[0, 1], [2, 3], [4, 5]].reduce( ( accumulator, currentValue ) => accumulator.concat(currentValue), [] ); ===> [0, 1, 2, 3, 4, 5]
속성으로 객체 분리
const people = [ { name: 'Alice', age: 21 }, { name: 'Max', age: 20 }, { name: 'Jane', age: 20 } ]; function groupBy(objectArray, property) { return objectArray.reduce( (acc, obj) => { const key = obj[property]; // 비어있다면 빈 배열 할당 if (!acc[key]) { acc[key] = []; } // 배열에 값 추가 acc[key].push(obj); // 누적 결과 반환 ( 이 값이 새롭게 acc에 담김 ) return acc; }, {}); // 초기 acc를 오브젝트로 초기화 } const groupedPeople = groupBy(people, 'age'); // { // 20: [ // { name: 'Max', age: 20 }, // { name: 'Jane', age: 20 } // ], // 21: [{ name: 'Alice', age: 21 }] // }
활용했던 예시
- 날짜배열과 시간배열이 있을 때, 날짜별로 시간배열을 갖는 오브젝트로 변환하기를 원할 때
const schedules = ["2021-02-10", "2021-02-11", "2021-02-12"]; const times = [["04:30", "05:00", "05:30", "08:00"], ["06:00", "06:30", "07:00", "07:30"], ["12:00", "12:30", "13:00", "13:30"]] const objs = schedules.reduce((a,c,i)=> Object.assign(a, {[c]:times[i]}) ,{}) /* { 2021-02-10: ["04:30", "05:00", "05:30", "08:00"] 2021-02-11: ["06:00", "06:30", "07:00", "07:30"] 2021-02-12: ["12:00", "12:30", "13:00", "13:30"] } */
- 학생 오브젝트에서 score 누적값 계산하기
class Student { constructor(name, age, enrolled, score) { this.name = name; this.age = age; this.enrolled = enrolled; this.score = score; } } const students = [ new Student('A', 29, true, 45), new Student('B', 28, false, 80), new Student('C', 30, true, 90), new Student('D', 40, false, 66), new Student('E', 18, true, 88), ]; // 학생들의 점수 평균 구하기 const sum = students.reduce((prev, cur)=>{ return prev+cur.score; }, 0} //===> 369 const avg = sum / students.length;
오브젝트 배열 → 오브젝트 형태로 변환
const nutrientGroupsUnitInfo = [ { "name": "비타민D", "unit": "IU" }, { "name": "철분", "unit": "mg" }, { "name": "비타민B", "unit": "mg" }, { "name": "멀티미네랄", "unit": "mg" }, { "name": "마그네슘", "unit": "mg" }, { "name": "밀크씨슬", "unit": "mg" }, { "name": "비타민C", "unit": "mg" }, { "name": "칼슘", "unit": "mg" }, { "name": "유산균", "unit": "억 CFU" }, { "name": "오메가3", "unit": "mg" } ] const result = nutrientGroupsUnitInfo.reduce((acc, current)=>({...acc, [current.name]: current.unit}), {}) console.log(result) // [LOG]: { // "비타민D": "IU", // "철분": "mg", // "비타민B": "mg", // "멀티미네랄": "mg", // "마그네슘": "mg", // "밀크씨슬": "mg", // "비타민C": "mg", // "칼슘": "mg", // "유산균": "억 CFU", // "오메가3": "mg" // }