Better way to sum a property value in an array

后端 未结 16 1783
遥遥无期
遥遥无期 2020-11-22 02:41

I have something like this:

$scope.traveler = [
            {  description: \'Senior\', Amount: 50},
            {  description: \'Senior\', Amount: 50},
             


        
16条回答
  •  半阙折子戏
    2020-11-22 03:16

    Just another take, this is what native JavaScript functions Map and Reduce were built for (Map and Reduce are powerhouses in many languages).

    var traveler = [{description: 'Senior', Amount: 50},
                    {description: 'Senior', Amount: 50},
                    {description: 'Adult', Amount: 75},
                    {description: 'Child', Amount: 35},
                    {description: 'Infant', Amount: 25}];
    
    function amount(item){
      return item.Amount;
    }
    
    function sum(prev, next){
      return prev + next;
    }
    
    traveler.map(amount).reduce(sum);
    // => 235;
    
    // or use arrow functions
    traveler.map(item => item.Amount).reduce((prev, next) => prev + next);
    

    Note: by making separate smaller functions we get the ability to use them again.

    // Example of reuse.
    // Get only Amounts greater than 0;
    
    // Also, while using Javascript, stick with camelCase.
    // If you do decide to go against the standards, 
    // then maintain your decision with all keys as in...
    
    // { description: 'Senior', Amount: 50 }
    
    // would be
    
    // { Description: 'Senior', Amount: 50 };
    
    var travelers = [{description: 'Senior', amount: 50},
                    {description: 'Senior', amount: 50},
                    {description: 'Adult', amount: 75},
                    {description: 'Child', amount: 35},
                    {description: 'Infant', amount: 0 }];
    
    // Directly above Travelers array I changed "Amount" to "amount" to match standards.
    
    function amount(item){
      return item.amount;
    }
    
    travelers.filter(amount);
    // => [{description: 'Senior', amount: 50},
    //     {description: 'Senior', amount: 50},
    //     {description: 'Adult', amount: 75},
    //     {description: 'Child', amount: 35}];
    //     Does not include "Infant" as 0 is falsey.
    

提交回复
热议问题