reduce
- 배열교차함수 reduce : 배열의 각 요소들을 주어진 콜백에 맞게 합산, 누적하여 하나의 결과값을 반환하는 함수
- reduce에 들어가는 callback
-> callback(accumulator, currentValue)
- accumulator: 어떤 데이터를 계속 쌓아가는 변수
- currentValue: 현재 루프회차에서 사용할 데이터
- reduce는 반복을 실행할 때마다 currentValue를 accumulator에 누적함
- reduce의 콜백함수 다음파라미터는 initialValue를 의미하며 반복문의 accumulator 시작값을 의미함
- 따라서 0을 시작값으로 두고 return a + b; 를 하면
0 + 1 + 2 + 3 + 4 + 5 + 6
- 시작값을 없애면 accumulator의 시작값이 0번인덱스로 지정되며
1 + 2 + 3 + 4 + 5 + 6
const userList = [
{
account: 'abc1234',
userName: '대길이',
job: '추노',
address: '서울',
hobbys: ['수영', '축구', '테니스'],
salary: 5400000,
age: 35,
},
{
account: 'banana',
userName: '빠나나',
job: '과일',
address: '서울',
hobbys: ['푸드파이팅', '테니스'],
salary: 9700000,
age: 18,
},
{
account: 'park1234',
userName: '주차왕',
job: '발렛파킹',
address: '경기',
hobbys: ['족구', '축구', '테니스', '영화감상'],
salary: 3900000,
age: 56,
},
{
account: 'fire',
userName: '불꽃남자카리스마',
job: '게이머',
address: '서울',
hobbys: ['독서', '테니스'],
salary: 7900000,
age: 42,
},
];
const appleBasket = [{
color: 'green',
sweet: 13
},
{
color: 'red',
sweet: 14
},
{
color: 'red',
sweet: 11
},
{
color: 'green',
sweet: 6
},
{
color: 'green',
sweet: 7
},
{
color: 'green',
sweet: 9
},
];
const resultTotalSweet = appleBasket
.reduce((totalSweet, apple) => {
return totalSweet + apple.sweet;
}, 0)
console.log(`사과 당도 총합: ${resultTotalSweet}`);
console.log('========================');
const countByColor = appleBasket.reduce((count, apple) => {
if(apple.color in count) {
count[apple.color]++;
} else {
count[apple.color] = 1;
}
return count;
}, {})
console.log(countByColor);
퀴즈
const traders = [
{
trader: {
name: "김철수",
city: "대전",
},
year: 2023,
value: 500000,
},
{
trader: {
name: "박영희",
city: "서울",
},
year: 2022,
value: 600000,
},
{
trader: {
name: "김철수",
city: "대전",
},
year: 2022,
value: 1200000,
},
{
trader: {
name: "박영희",
city: "서울",
},
year: 2023,
value: 650000,
},
{
trader: {
name: "뽀로로",
city: "부산",
},
year: 2023,
value: 800000,
},
{
trader: {
name: "루피",
city: "대전",
},
year: 2022,
value: 780000,
},
];
const TradeIn2022 = traders
.filter((user) => user.year === 2022)
.map((user) => user.trader);
console.log(TradeIn2022);
const city = traders.map((user) => user.trader.city);
const duplicatedCity = [...new Set(city)];
console.log(duplicatedCity);
const DaejeonWorkingTrader = traders
.filter((user) => user.trader.city === "대전")
.map((user) => user.trader);
console.log(DaejeonWorkingTrader);
const tradersAllName = traders.map((user) => user.trader.name);
const duplicatedtradersAllName = [...new Set(tradersAllName)];
console.log(duplicatedtradersAllName);
let total = 0;
traders
.filter(user => user.trader.city === '서울')
.map(user => user.value)
.forEach(value => total += value)
console.log(total);
let sum1 = 0;
traders
.filter((trs) => trs.trader.city === "대전")
.forEach((trs) => (sum1 += trs.value));
console.log(sum1);
const BusanTraders = traders
.filter((trs) => trs.trader.city === "부산")
.map((trs) => trs.trader.name);
const duplicatedBusanTraders = [...new Set(BusanTraders)];
console.log(duplicatedBusanTraders);
const highvalue = traders
.reduce((max, current) => { max.value > current.value ? max : current});
const result = highvalue.trader
console.log(result);
let citiesValues = traders.reduce((count, cities) => {
const city = cities.trader.city;
if (cities.trader.city in count) {
count[city] += cities.value;
} else {
count[city] = cities.value;
}
return count;
}, {});
console.log(citiesValues);
const trsYear = traders
.filter((trs) => trs.value >= 700000)
.reduce((years, trs) => {
if (trs.year in years) {
years[trs.year] += trs;
} else {
years[trs.year] = [trs];
}
return years;
}, {});
console.log(trsYear);
let sum = 0;
traders.forEach((user) => (sum += user.value));
let avg = sum / traders.length;