I'm trying to calculate the total amount of hours from an array. The array contains a series of sessions that take different time to conclude. The problem that I might have, is that the hour field is a string.
This is how it looks like:
[
{ "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"
}
]
And the totalt should amount to 5,5 hours.
I have tried to filter the array:
computed: {
hours(){
var hours = 0
this.oft.filter((item => {
hours = item.hours
}))
return hours
}
},
But it returns a ridiculous high number.
CodePudding user response:
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);
},
`
CodePudding user response:
You can use reduce
:
const arr= [{ "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"}]
function total(a) {
return a.reduce(( accumulator, currentValue ) => accumulator Number(currentValue.hours), 0)
}
console.log(total(arr))
CodePudding user response:
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)