자바스크립트 reduce 또한 map과 마찬가지로 순서가 있는 배열에 사용되는 메소드입니다.
사용되는 방식은 아래와 같습니다.
const array1 = [1, 2, 3, 4];
// 0 + 1 + 2 + 3 + 4
const initialValue = 0;
const sumWithInitial = array1.reduce(
(accumulator, currentValue) => accumulator + currentValue,
initialValue
);
reduce를 사용하고 나온 반환값은 reduce계산을 마친 누적계산의 결과값이 됩니다.
map은 배열의 재구성에 초점이 맞춰져있다면 reduce는 누적한 값을 반환하는데 초점이 맞춰져있습니다.
우선 map의 예시를 보겠습니다.
const a = [1,2,3,4,5]
const b = a.map((data) => {
if (data%2) {
return '홀수'
}
return '짝수'
})
console.log(b) // ['홀수','짝수','홀수','짝수','홀수']
배열안의 각각의 값에 맞는 값으로 새로운 배열이 만들어져 반환합니다.
[1,2,3,4,5] => ['홀수','짝수','홀수','짝수','홀수']
reduce의 예시를 보겠습니다.
const a = [1,2,3,4,5]
const b = a.reduce((accumulator, currentValue) => {
return accumulator+currentValue
})
console.log(b) // 15
b의 값은 a배열에 있는 모든 값을 더한 값이 됩니다.
reduce의 실행순서를 살펴보겠습니다.
const a = [1,2,3,4,5]
const b = a.reduce((accumulator, currentValue) => {
console.log(`accumulator : ${accumulator}`)
return accumulator+currentValue
})
console.log(b)
/*
accumulator : 1
accumulator : 3
accumulator : 6
accumulator : 10
15
*/
accumulator에 currentValue값이 순차적으로 더해짐을 확인할 수 있습니다.
그렇다면 이 reduce를 어디에 사용할까요?
1. 배열의 요소 값 누적하기
const a = [{k:1},{k:2},{k:3}]
const b = a.reduce((accumulator,currentValue) => {
return accumulator+currentValue.k
},0)
console.log(b) // 6
배열에 저장된 객체의 한 요소를 더하는데 사용합니다. 이럴경우 initialValue값을 초기화해줘야합니다.
위의 예시에선 reduce의 callback이 끝나고 0으로 초기화한 것을 확인할 수 있습니다.
2. 중첩된 배열 펼치기
const a = [[1,2],[3,4],[5,6]]
const b = a.reduce((accumulator,currentValue) => {
return accumulator.concat(currentValue)
},[])
console.log(b) // [ 1, 2, 3, 4, 5, 6 ]
3. 속성으로 객체 분류하기
const a = [{name:'doyeon',age:20},{name:'doyeonism',age:21},{name:'jack dawson',age:21}]
const b = a.reduce((accumulator,currentValue) => {
const key = currentValue[`age`];
if (!accumulator[key]) {
accumulator[key] = [];
}
accumulator[key].push(currentValue)
return accumulator
},{})
console.log(b)
/*
{
'20': [ { name: 'doyeon', age: 20 } ],
'21': [ { name: 'doyeonism', age: 21 }, { name: 'jack dawson', age: 21 } ]
}
*/
배열에서 나이가 20인 사람과 21인 사람을 각각 나눠 저장했습니다.
4. 배열의 중복 제거
const a = [1,2,1,2,1,2,1,3,2,3,4,5,6,1,2,4,6,5,6]
const b = a.sort().reduce((accumulator,currentValue) => {
const length = accumulator.length
if (length === 0 || accumulator[length - 1] !== currentValue){
accumulator.push(currentValue);
}
return accumulator
},[])
console.log(b) // [ 1, 2, 3, 4, 5, 6 ]
배열안의 중복된 값을 제거할 수 있습니다.
이 외에 다양한 곳에 reduce를 사용하여 깔끔한 코드를 작성할 수 있습니다.
'JavaScript' 카테고리의 다른 글
--dev, -D 같은 devDependency를 왜 사용할까? (0) | 2022.12.16 |
---|---|
리액트 a태그에 target='blank'를 적용하면 생기는 에러 (0) | 2022.12.11 |
자바스크립트 map에 대해 알아보고 간단한 예시를 살펴보자 (0) | 2022.12.02 |
API란 무엇이고 어떻게 호출할까? (0) | 2022.11.27 |
유용한 자바스크립트 문법을 배워보자 (0) | 2022.11.19 |