Better way to sum a property value in an array

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

    Here is a one-liner using ES6 arrow functions.

    const sumPropertyValue = (items, prop) => items.reduce((a, b) => a + b[prop], 0);
    
    // usage:
    const cart_items = [ {quantity: 3}, {quantity: 4}, {quantity: 2} ];
    const cart_total = sumPropertyValue(cart_items, 'quantity');
    

提交回复
热议问题