[Vuejs]-How can I calculate the totalt amount of hours?

1👍

I observed your input the id 3 hours couldn’t be converted into a number coz of the way it is presented it should be 0.5 instead of 0,5 and if you want to find the total number of hours filter is not your method you want single value base on given array but filter returns new array base on condition you should use reduce the code would be like this `

hours()
{
return this.arr.reduce((acc, curr) => {
        acc = acc + +curr.hours;
        return acc;
      }, 0);
},

`

0👍

you can do it with reduce

be aware that 0,5 is not a valid number so you have to replace , with .in order to parse it correctly

const data= [

    { "id": 1,
    "exercise": "1.1",
    "name": "Session one",
    "hours": "1"
    },
    { "id": 2,
    "exercise": "1.2",
    "name": "Session two",
    "hours": "4"
    },
    { "id": 3,
    "exercise": "1.3",
    "name": "Session three",
    "hours": "0,5"
    }
]


const total = data.reduce((res, {hours}) => res + parseFloat(hours.replace(',', '.')), 0.)

console.log(total)

Leave a comment