함수 reduce()

(함수 array reduce()에서 넘어옴)
reduce

1 JavaScript[ | ]

const numbers = [100, 20, 10];
const result = numbers.reduce(function(total, num) {
  return total + num;
});
console.log( result ); // 130 = 100 + 20 + 10
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
const numbers = [100, 20, 10];
const result = numbers.reduce(function(total, num) {
  return total - num;
});
console.log( result ); // 70 = 100 - 20 - 10

2 PHP[ | ]

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

3 Python[ | ]

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

4 같이 보기[ | ]

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}