Better way to sum a property value in an array

后端 未结 16 1455
遥遥无期
遥遥无期 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:35

    You can do the following:

    $scope.traveler.map(o=>o.Amount).reduce((a,c)=>a+c);
    
    0 讨论(0)
  • 2020-11-22 03:35

    It's working for me in TypeScript and JavaScript:

    let lst = [
         { description:'Senior', price: 10},
         { description:'Adult', price: 20},
         { description:'Child', price: 30}
    ];
    let sum = lst.map(o => o.price).reduce((a, c) => { return a + c });
    console.log(sum);

    I hope is useful.

    0 讨论(0)
  • 2020-11-22 03:37

    I always avoid changing prototype method and adding library so this is my solution:

    Using reduce Array prototype method is sufficient

    // + operator for casting to Number
    items.reduce((a, b) => +a + +b.price, 0);
    
    0 讨论(0)
  • 2020-11-22 03:37

    can also use Array.prototype.forEach()

    let totalAmount = 0;
    $scope.traveler.forEach( data => totalAmount = totalAmount + data.Amount);
    return totalAmount;
    
    0 讨论(0)
提交回复
热议问题