An array reduce function allows you to iteratively reduce an array to a single value using a callback function. PHP: array_reduce(), JavaScript: Array.prototype.reduce()
An array reduce function allows you to implement a reduce algorithm by using a callback function to iteratively reduce an array to a single value.
Documentation
- PHP:
array_reduce()
- JavaScript:
Array.prototype.reduce()
- Scala:
Array.reduce()
Example
Consider this simple code, which will result in calculating a total value of 15 by calling the sum()
function 5 times.
PHP:
function sum($total, $item) {
return $total + $item;
}
$data = array(1, 2, 3, 4, 5);
$result = array_reduce($data, 'sum', 0);
JavaScript:
const sum = (total, item) => total + item;
const data = [1, 2, 3, 4, 5];
const result = data.reduce(sum, 0);
The sum()
function will be called 5 times, once for each element of the array:
The first time, it uses the starting value of
0
that we provided, and processes the first item:sum(0, 1) // returns 1
The second time, it uses the return value from the first call, and processes the second item:
sum(1, 2) // returns 3
Each time after that, it uses the previous return value, and processes the next item in the array:
sum(3, 3) // return 6 sum(6, 4) // returns 10 sum(10, 5) // returns 15
And finally, the value returned from the last call is returned back as the result of the array_reduce() function:
$result = 15;