Page 100 - JavaScript
P. 100

See Arrays are Objects for a detailed analysis.


        Reducing values


        5.1


        The reduce() method applies a function against an accumulator and each value of the array (from
        left-to-right) to reduce it to a single value.


        Array Sum


        This method can be used to condense all values of an array into a single value:


         [1, 2, 3, 4].reduce(function(a, b) {
           return a + b;
         });
         // → 10


        Optional second parameter can be passed to reduce(). Its value will be used as the first argument
        (specified as a) for the first call to the callback (specified as function(a, b)).


         [2].reduce(function(a, b) {
           console.log(a, b); // prints: 1 2
           return a + b;
         }, 1);
         // → 3



        5.1


        Flatten Array of Objects


        The example below shows how to flatten an array of objects into a single object.


         var array = [{
             key: 'one',
             value: 1
         }, {
             key: 'two',
             value: 2
         }, {
             key: 'three',
             value: 3
         }];

        5.1


         array.reduce(function(obj, current) {
           obj[current.key] = current.value;
           return obj;
         }, {});

        6

        https://riptutorial.com/                                                                               57
   95   96   97   98   99   100   101   102   103   104   105