In the javascript code below in the function execute a select on a db (using typerom) from which an array formatted as follows:
JSON Data Example:
{
"id": 1,
"nome": "prova2",
"datacreazione": "2021-09-05T08:41:29.000Z",
"costo": 23,
"ore": "08:00",
"IdPreventivo": 1,
"IdUtente": 2
},
{
"id": 2,
"nome": "prova2",
"datacreazione": "2021-09-06T08:38:26.000Z",
"costo": 23,
"ore": "08:00",
"IdPreventivo": 1,
"IdUtente": 2
}
the hours (ore
) field contains the total hours of the activity carried out what I want to do is calculate the total hours by adding and exegundo a sum of all the ore
entered in that field for each element of the array, the hours they are in the format HH: MM, how can I go about doing this?
AttivitaprevService.js
@Injectable()
export class AttivitaprevService {
constructor(
@InjectRepository(Attivitaprev) private repo: Repository<Attivitaprev>
) {}
create(dto: CreateAttivitaprevDto) {
return this.repo.save(dto);
}
findAll() {
return `This action returns all attivitaprev`;
}
async findOne(id: number) {
return await this.repo.find({
where: { IdPreventivo: id },
});
}
sumofhour = (time1, time2) => {
let [h1, m1] = time1.split(':')
let [h2, m2] = time2.split(':')
return ((+h1 + (+m1 / 60)) + (+h2 + (+m2 / 60)))
}
async totaleore(id: number) {
var values= await this.repo.find({
where: { IdPreventivo: id },
});
return values;
}
..
Please see the Array.reduce
implementation.
const data = [
{
"id": 1,
"nome": "prova2",
"datacreazione": "2021-09-05T08:41:29.000Z",
"costo": 23,
"ore": "08:30",
"IdPreventivo": 1,
"IdUtente": 2
},
{
"id": 2,
"nome": "prova2",
"datacreazione": "2021-09-06T08:38:26.000Z",
"costo": 23,
"ore": "08:30",
"IdPreventivo": 1,
"IdUtente": 2
}
]
sumofhour = () => {
const sum = data.reduce((acc, curr) => {
let [h1, m1] = curr.ore.split(':');
acc += (+h1 + (+m1 / 60));
return acc;
}, 0)
return sum;
};
console.log(sumofhour());