The Array.reduce() is an inbuilt TypeScript function which is used to apply a function against two values of the array as to reduce it to a single value.
Syntax:
array.reduce(callback[, initialValue])
Parameter: This method accept two parameter as mentioned and described below:
- callback : This parameter is the Function to execute on each value in the array.
- initialValue : This parameter is the Object to use as the first argument to the first call of the callback.
Return Value: This method returns the reduced single value of the array.
Below examples illustrate the Array reduce() method in TypeScript
Example 1:
JavaScript
<script> // Driver code var arr = [ 11, 89, 23, 7, 98 ]; // use of reduce() method var val = arr.reduce( function (a, b) { return a + b; }); // printing element console.log( val ); </script> |
Output:
228
Example 2:
JavaScript
<script> // Driver code var arr = [2, 5, 6, 3, 8, 9]; var val; // use of reduce() method val = arr.reduce( function (a, b) { return a*b/2; }); // printing element console.log( val ); </script> |
Output:
405