Saturday 15 September 2018

JavaScript: Array: reduce: combine elements of array

'reduce' function is used to combine elements of array using given combiner function.

Syntax
arr.reduce(callback[, initialValue])

callback function takes four arguments.

Argument
Description
previousValue

The value previously returned in the last invocation of the callback, or initialValue, if supplied.
currentValue

The current element being processed in the array.
currentIndex

The index of the current element being processed in the array. Starts at index 0, if an initialValue is provided, and at index 1 otherwise.
array
The array reduce was called upon.

initialValue
It is optional, Value to use as the first argument to the first call of the callback.

function add(x, y){
         return x+y;
}               
var sumOfEle = arr1.reduce(add, 0);

Above statements are used to calculate sum of elements of the array.
        
function mul(x, y){
         return x*y;
}
var mulOfEle = arr1.reduce(mul, 1);

Above statements are used to compute multiplication of elements in array.                        
                          
function max(x, y){
         return ((x>y)?x:y);
}
var maximum = arr1.reduce(max);

Above statements are used to compute maximum value in the array.
                          
reduce.html
<!DOCTYPE html>

<html>

<head>
    <title>Array reduce example</title>
</head>

<body>
    <script type="text/javascript">
        var arr1 = [12, 43, 2, 3, 98, 6];

        function add(x, y) {
            return x + y;
        }

        function mul(x, y) {
            return x * y;
        }

        function max(x, y) {
            return ((x > y) ? x : y);
        }

        var sumOfEle = arr1.reduce(add, 0);
        var mulOfEle = arr1.reduce(mul, 1);
        var maximum = arr1.reduce(max);

        document.write("Sum of elements in array is " + sumOfEle + "<br />");
        document.write("Multiplication of elements in array is " + mulOfEle + "<br />");
        document.write("Maximum number in array is " + maximum + "<br />");
    </script>
</body>

</html>




Previous                                                 Next                                                 Home

No comments:

Post a Comment