connecting dots

JS | reduce - summing an array, for...of 본문

Online Class/Udemy

JS | reduce - summing an array, for...of

dearsuhyun 2024. 6. 13. 10:48

reduce

Executes a reducer function on each element of the array, resulting in a single value.

배열을 가져다가 점차 줄여가다가 하나의 값만 남기는 것

 

[3, 5, 7, 9, 11].reduce((accumulator, currentValue) => {
  return accumulator + currentValue;
});
callback accumulator currentValue return value
first call 3 5 8
second call 8 7 15
third call 15 8 24
fourth call 24 11 35

 

accumulator: 줄여나가야 하는 대상, 총 합계

currentValue: 각각의 개별 요소

 

인수 추가 가능

const evens = [2, 4, 6, 8];
evens.reduce((sum, num) => sum + num, 100)

// 두 번째 인수 100은 sum에 대한 초기값으로 사용됨
// 즉 100에 num을 더해주는 것

 

for ... of

for...of 문은 배열이나 다른 iterable 객체(예: 문자열, NodeList 등)의 요소를 반복(iterate)하기 위해 사용됩니다. 

const prices = [100, 200, 300, 400];

for (let price of prices) {
  console.log(price);
}
// 100
// 200
// 300
// 400

const prices = [100, 200, 300, 400];

const sum = 0;
for (let price of prices) {
  sum += price
}
console.log(sum) // 1000

 

for (let price of prices)는 prices의 각 요소를 하나씩 가져와 price 변수에 할당함

 

--> reduce

const total = prices.reduce((sum, price) => {
  return sum + price
}
console.log(total) // 1000

 

최소값 구하기

const minPrice = prices.reduce((min, price) => {
  if (price < min) {
    return price;
    }
    else return min;
})

console.log(minPrice) // 100
반응형