Get the sum of all specified elements in an array of objects

后端 未结 5 1853
一个人的身影
一个人的身影 2021-01-28 12:17

I have an array of objects as folllows

[
    {\"width\":128.90663423245883,\"height\":160,\"X\":0,\"Y\":140},
    {\"width\":277.0938568683375,\"height\":263,\"X         


        
5条回答
  •  猫巷女王i
    2021-01-28 12:52

    Here is an example using a slice to first return the array with the correct length and the a reduce to return the sum

    const getSum = (objNum, arr) => {
      const newArr =  arr.slice(0, objNum - 1)
      return newArr.reduce((current, next) => {
        return current + next.width;
      }, 0)
    }
    

    and in ES5

    var getSum = (objNum, arr) => {
      vat newArr =  arr.slice(0, objNum - 1)
      return newArr.reduce(function(current, next) {
        return current + next.width;
      }, 0)
    }
    

    and in 1 line

    const getSum = (objNum, arr) => arr.slice(0, objNum - 1).reduce((current, next) =>  current + next.width, 0)
    

提交回复
热议问题