NOTE
Array.prototype.reduce()
ssund
2023. 4. 20. 14:29
reduce라고 하면 떠올리는 것 ! 누산기
누산이란 ? 소계(小計)를 계속하여 덧붙여 합산함. 또는 그런 합계를 말한다.
배열의 모든 원소에 대해 특정한 연산을 순차적으로 적용할 때 사용한다.
배열의 원소 합을 구하거나, 배열의 길이, 원소의 최대값을 구할 수있다.
reduce(callbackFn) //initialValue를 생략할수도 있다.
reduce(callbackFn, initialValue)
배열의 원소들의 전체 합 구하기
reduce callback 함수안에 accumulator가 계산된 이전값,
currentValue는 현재 인덱스에 해당하는 배열원소의 값이 된다.
const array1 = [1, 2, 3, 4];
// 0 + 1 + 2 + 3 + 4
const initialValue = 0;
const sumWithInitial = array1.reduce(
(accumulator, currentValue) => (accumulator + currentValue),
initialValue
);
console.log(sumWithInitial);
// Expected output: 10
오브젝트가 요소로 있는 배열의 특정값도 합산할 수 있다.
const testArr = [{value: 1}, {value : 2}, {value: 3}, {value: 4}];
testArr.reduce((acc, curr) => acc + curr.value, 0) //10
배열의 원소의 최대값 구하기
Math.max 메소드를 이용하여 이전값과 현재인텍스 요소값을 비교하여 최대값을 구할 수 있다.
const array1 = [1, 10, 3, 4, 9, 99];
const sumWithInitial = array1.reduce(
(accumulator, currentValue) => Math.max(accumulator, currentValue)
);
console.log(sumWithInitial); //99
배열의 최대값은 reduce를 이용하지 않고 Math.max 메소드를 이용해서 간단하게 구할수 있다.
const testArr = [1, 2, 3, 5, 99, 9];
console.log(Math.max(testArr)); // NaN
console.log(Math.max(...testArr)); // 99
배열 합치기
배열에 요소로 들어가있는 배열을 합쳐서 하나의 배열로 리턴할 수 있다.
각각의 요소를 돌며 배열요소를 concat을 이용하여 acc 배열에 합친다.
const testArray = [[1, 2], [3, 4], [5, 6]];
const reducedArray = testArray.reduce((acc, curr) => acc.concat(curr));
console.log(reducedArray); // [1, 2, 3, 4, 5, 6]
딕셔너리 만들기
빈 객체를 초기값으로 정해준다.
const stringArr = ['aa', 'bb'];
const dictionary = stringArr.reduce((acc, curr) => {
acc[curr] = curr
return acc;
}, {});
console.log(dictionary);
딕셔너리를 만들고 동일한 요소가 몇개인지 카운트하는 로직
const testCountedArr = ['A', 'B', 'A', 'A', 'B'];
testCountedArr.reduce((acc, curr) => {
if(curr in acc) {
// 만약 배열에 해당 요소가 있으면 숫자 올린다.
acc[curr]++
} else {
// 배열에 해당 요소가 없으면 default value = 1을 준다.
acc[curr] = 1
}
return acc;
}, {});
참고
https://m.blog.naver.com/wideeyed/221877924629
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce