함수 reduce()

reduce

1 JavaScript[ | ]

JavaScript
Copy
const numbers = [100, 20, 10];
const result = numbers.reduce(function(total, num) {
  return total + num;
});
console.log( result ); // 130 = 100 + 20 + 10
130 
JavaScript
Copy
const numbers = [100, 20, 10];
const reducer = (accumulator, currentValue) => accumulator + currentValue;
console.log(numbers.reduce(reducer));    // 130 = 100 + 20 + 10
console.log(numbers.reduce(reducer, 5)); // 135 = 5 + 100 + 20 + 10
130 
135 
JavaScript
Copy
const numbers = [100, 20, 10];
const result = numbers.reduce(function(total, num) {
  return total - num;
});
console.log( result ); // 70 = 100 - 20 - 10
70 

2 PHP[ | ]

PHP
Copy
$a = [2, 3, 4, 5];
$result = array_reduce($a, function($carry, $i) {
    $carry += $i;
    return $carry;
});
echo $result; # 14
Loading
PHP
Copy
$a = [2, 3, 4, 5];
$result = array_reduce($a, function($carry, $i) {
    $carry *= $i;
    return $carry;
}, 1);
echo $result; # 120
Loading

3 Python[ | ]

Python
Copy
from functools import reduce
a = [2, 3, 4, 5]
print( reduce((lambda x, y: x*y), a) ) # 120
Loading

4 같이 보기[ | ]