Better way to sum a property value in an array

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

I have something like this:

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


        
16条回答
  •  -上瘾入骨i
    2020-11-22 03:11

    From array of objects

    function getSum(array, column)
      let values = array.map((item) => parseInt(item[column]) || 0)
      return values.reduce((a, b) => a + b)
    }
    
    foo = [
      { a: 1, b: "" },
      { a: null, b: 2 },
      { a: 1, b: 2 },
      { a: 1, b: 2 },
    ]
    
    getSum(foo, a) == 3
    getSum(foo, b) == 6
    

提交回复
热议问题