Array.prototype.reduce()

.reduce()는 많은 데이터(배열)를 가져와 만든 단하나의 데이터반환한다. .reduce().filter().map()과 같은 higher-order function 즉 고차함수다. 무슨뜻이냐면 함수를 argument로 받는다는거다.

array.reduce(<function>/*,<starting-value>*/);

.reduce()메소드는 함수와, 시작값 두개의 인자를 받는다. 시작값은 말그대로 시작값이고 빈배열에서 메소드를 사용할때 시작값이 제공되지 않으면 TypeError가 발생한다. 인자로 받은 함수는 4개의 인자를 받는다.

  • previousValue
  • currentValue
  • currentIndex
  • array

const iceCream = [
    {name:'minwoo', gallonsEaten:20},
    {name:'sulhyeon', gallonsEaten:15},
    {name:'hodong', gallonsEatens:2000}
];

const totalEaten = iceCream.reduce((prev, curr) => (prev + curr.gallonsEaten),0);

console.log(totalEaten); // => 2035

results matching ""

    No results matching ""