Array.prototype. reduce()

차노·2023년 7월 28일
0

JS

목록 보기
38/96

The reduce() method executes a user-supplied "reducer" callback function on each eleent of the array, in order, passing in the return value from the calculation on the preceding element.
The final result of running hte reducer across all elements of the array is a signal value.

The first time that the callback is run there is no "return value of the previous calcuation". If supplied, an initial value may be used in its place. Otherwise the array element at index 0 is used as the initial value and iteration starts from the next element (index 1 instead of index 0).

Perhaps the easiest-to-understand case for reduce() is to return the sume of all elements in an array.

The reducer walks through the array element-by-element, at each step adding the current array value to the result from the previous step (this result is the running sum of all the previous steps) - until there are no more elements to add.

Description

The reduce() method is an iterative method. It runs a "reducer" callback function over all elements in the array, in ascending-index order, and accumulates them into a single value.

Every time, the return value of callbackFn is passed into callbackFn again on next invocation as accumulator. The final value of accumulator (which is the value returned from callbackFn on the final iteration of the array) becomes the return value of reduce().

callbackFn is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays.

Unlike other iterative methods, reduce() does not accept a thisArg argument. callbackFn is always calld with undefined as this, which gets substituted with globalThis if callbackFn is not-strict. Array.prototype.reduce() is a **higher-order function** in JavaScript that is used to **accumulate or combine** the elements of an array **into** a single value. >_ reduce()는 배열의 요소를 하나의 값으로 합치거나 축적할 때 사용되는 자바스크립트의 higher-order 함수이다._ It iterates through each element of the array and applies a specified function that performs some operation on the element and the accumulated result. >_ 배열의 요소를 통해 **자동화**하고 요소와 축적된 결과에 일정의 작업을 수행하는 특정 함수를 적용한다. _ ![](https://velog.velcdn.com/images/chano94/post/50f96a07-023b-4c79-9a87-1934da524d04/image.png)
  • callback : A function that is executed for each element in the array.

    배열 각각의 요소를 실행하는 함수

: It takes four arguments => accumulator, currentValue, currentIndex, and the array itself.

  • initialValue: An optional initial value that will be used as the initial accumulator value for the first iteration.

    처음 자동화의 최초의 accumulator 값으로서 사용될 선택적 초기값.

I asked GPT about this.

0개의 댓글