TransWikia.com

Handling arrays of hours

Stack Overflow Asked by Matheus Alves on December 18, 2020

I’m needing some help to handle dates with jquery…

I have a list of hours:

    const listHours = [
        '08:00', '08:30', '09:00', '09:30', '10:00', '10:30', '11:00', '11:30', '12:00', '12:30', '13:00', '13:30', '14:00', '14:30', '15:00', '15:30', '16:00', '16:30', '17:00', '17:30', '18:00', '18:30', '19:00', '20:00', '20:30', '21:00', '21:30', '22:00', '22:30', '23:00', '23:30', '00:00'
    ]

And then, through a function, I should receive another array like this …

Just an example:

enter image description here

    function createDataListHour(hoursList, timesToRemove){

}

This function must receive this array of arrays and look for the period between them. An example, I will receive 08:00 until 10:00 and 11:00 until 14:30, as in the print above. So my function should take all the times that are between and remove them from my other array … In that case, I should remove the hours 08:00, 08:30, 09:00, 09:30, 10:00 and also 11: 00, 11:30, 12:00, 12:30, 13:00, 13:30, 14:00, 14:30 and in the end I return my "listHours" array without all those hours.

Like this:

'10:30', '15:00', '15:30', '16:00', '16:30', '17:00', '17:30', '18:00', '18:30', '19:00', '20:00', '20:30', '21:00', '21:30', '22:00', '22:30', '23:00', '23:30', '00:00'

My English is not the best and I am having difficulties even explaining my problem, so if anyone can suggest changes in this topic, I will be grateful.

One Answer

Here you go :)

I recommend reading up on this here: https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

const listHours = [
    '08:00', '08:30', '09:00', '09:30', '10:00', '10:30', '11:00', '11:30', '12:00', '12:30', '13:00', '13:30', '14:00', '14:30', '15:00', '15:30', '16:00', '16:30', '17:00', '17:30', '18:00', '18:30', '19:00', '20:00', '20:30', '21:00', '21:30', '22:00', '22:30', '23:00', '23:30', '00:00'
]

let remove = [
    ['08:00', '10:00'],
    ['11:00', '14:30']
]

function createDataListHour(hoursList, timesToRemove){
    timesToRemove.forEach(element => {
        let startIndex = hoursList.findIndex((el) => el === element[0]);
        let endIndex = hoursList.findIndex((el) => el === element[1]);
        hoursList.splice(startIndex, endIndex - startIndex + 1)
    });
    return hoursList;
}

console.log(createDataListHour(listHours, remove))

Correct answer by MincedMeatMole on December 18, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP