Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

195
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda