본문 바로가기

Study/JS

JS - Array.prototype.reduce() 구현하기

reduce()** **메서드는 배열의 각 요소에 대해 주어진 **리듀서**(reducer) 함수를 실행하고, 하나의 결과값을 반환합니다. - mdn

 

const array1 = [1, 2, 3, 4];

// 0 + 1 + 2 + 3 + 4
const initialValue = 0;
const sumWithInitial = array1.reduce(
  (previousValue, currentValue) => previousValue + currentValue,
  initialValue
);

console.log(sumWithInitial);
// expected output: 10

다음과 같이 배열의 총 합을 구할때 많이 사용하는 reduce 함수를 직접 구현해보겠습니다.

 

 

const arr = [1,2,3,4,5];

먼저 임의의 배열을 먼저 추가해줍니다.

 

Array.prototype.reduce2 = function(callback) {
	return null;
}

현업에서는 reduce2 = () => { ... } 와 같이 함수를 생성하지만 저는 웹브라우저 콘솔에서

테스트를 할것이라 다음과 같이 임의의 함수(reduce2)를 생성했습니다.

 

Array.prototype.reduce2 = function(callback) { 
	console.log(this);
  return null;
}

console.log(arr.reduce2));

reduce2 함수에서 arr에 접근하는 방법은 this를 사용하는 것입니다.

 

위 코드를 실행하면 다음과 같은 결과를 얻을 수 있습니다.

이제 arr에 접근하는 방법을 알았으니 코드를 작성해보겠습니다.

 

Array.prototype.reduce2 = function(callback) {
  let result = 0;
  for(let i = 0; i < this.length; i++){
    result = callback(result, this[i]);
  }
  return result;
}

console.log(
  arr.reduce2((prev,curr)=>prev+curr)
)

 

 

다음과 같이 임의의 변수 result에 result + arr[index]를 더한 값을 넣어주면 총 합을 리턴합니다.

'Study > JS' 카테고리의 다른 글

JS - Array.prototype.map() 구현하기  (0) 2022.11.02
JS - Array.prototype.filter() 구현하기  (0) 2022.11.02
클로저 (Closure)  (0) 2022.10.05
진수변환  (0) 2022.09.29
JSON  (0) 2022.09.29