Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

196
Vistas
How can I calculate the totalt amount of hours?

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.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

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);
},

`

about 4 years ago · Juan Pablo Isaza Denunciar

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)

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda