Issue encountered while generating time slots in JavaScript

For my upcoming project, I plan to divide the day into two-hour time slots.

start_time=10:00
end_time=24:00

The desired format for these time slots is similar to this example:

[ [10:00,12:00], [12:00,14:00], [14:00,16:00] ] ...

To achieve this, I am utilizing the following function:

function calculate_time_slot(start_time, end_time, interval = "120") {
    var i, formatted_time;
    var time_slots = new Array();
    for (var i = start_time; i <= end_time; i = i + interval) {
        formatted_time = convertHours(i);
        time_slots.push(formatted_time);
    }
    return time_slots;
}

However, the current output is not in the desired pairing format:

[
  '10:00', '12:00',
  '14:00', '16:00',
  '18:00', '20:00',
  '22:00', '24:00'
]

I am seeking guidance on how to adjust the function to generate results in the preferred pair format like so:

[ [10:00,12:00], [12:00,14:00], [14:00,16:00] ] ...

Answer №1

Within the loop, perform calculations for two properly formatted times: one for the start time of the slot and another for the end time of the slot:

function calculate_time_slot(startTime, endTime, interval = 120) {
  const timeSlots = [];
  for (let i = startTime; i < endTime; i += interval) {
    const formattedBegin = convertHours(i);
    const formattedEnd = convertHours(i + interval);
    timeSlots.push([formattedBegin, formattedEnd]);
  }
  return timeSlots;
}

Ensure that when setting the value of interval, it is defined as a number rather than a string to enable addition instead of concatenation.

Answer №2

If you want to manipulate time slots, consider using the reduce() method within the calculate_time_slot function:

let time_slots = ["10:00", "12:00", "14:00", "16:00", "18:00", "20:00", "22:00", "24:00"];

time_slots = time_slots.reduce((acc, cur, i, arr) => {
  if (i < arr.length - 1) {
    acc.push([`${cur}`, `${arr[i + 1]}`]);
  }
  return acc;
}, []);

console.log(time_slots);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue detected with Bundler: Configuration object is not valid. The initialization of Webpack used a configuration object that does not align with the API schema

I am currently struggling to make my bundler compile properly. When trying to get it working, I encountered this error message in my terminal along with my webpack.config.js file. Here is the issue reported by the terminal: Invalid configuration object. ...

Combine Three.js with KineticJS to export the KineticJS layer as a THREE.texture

Is there a way to convert a KineticJS layer into a ThreeJS texture in order to apply it to a plane? I want to take advantage of KineticJS's text manipulation features within my 3D scene. Currently, I am trying to achieve this with the following line ...

Can someone show me an efficient way to inspect the elements within an array?

I need to verify if a character array consists entirely of zeros. I attempted the following approach, but it was unsuccessful: char array[8]; // ... if (array == {'0','0','0','0','0','0','0 ...

What is the correct way to use a Higher Order Component to wrap the child components of a parent and display them in React?

Starting with a simple example that can be easily solved using React.cloneElement, but wanting more freedom and complexity in the project, I am looking for an alternative solution. The goal is to enhance the children of a Parent component with additional ...

Using Java, convert a JSONObject to another Required JSONObject by mapping the AccountId

**I have successfully converted a JSONObject using Java with the following code. I have searched extensively for how to do this conversion and finally achieved it.** { "result": { "accountnames": [{ "accoun ...

Guide to sending AJAX requests to SQL databases and updating the content on the webpage

One way I have code to showcase a user's name is by using the following snippet: <div><?php echo 'My name is ' . '<span id="output">' . $_SESSION['firstname'] . '</span>' ?></div> ...

Having trouble receiving accurate intellisense suggestions for MongoDB operations

Implementing communication between a node application and MongoDB without using Mongoose led to the installation of typing for both Node and MongoDB. This resulted in the creation of a typings folder with a reference to index.d.ts in the server.ts file. In ...

Needing to utilize the provide() function individually for every service in RC4

In Beta, my bootstrapping code was running smoothly as shown below: bootstrap(App, [ provide(Http, { useFactory: (backend: XHRBackend, defaultOptions: RequestOptions, helperService: HelperService, authProvider: AuthProvider) => new CustomHt ...

What is the best way to determine the total number of rows in a JSON file?

Here is the JSON data I have: [0:{name:"jason",height:"150cm"}, 1:{name:"henry",height:"178cm"}] In my function, I am attempting to create a for loop like this: function DrawTable(output) { var ...

Passing values to the next page is not functioning as expected

I'm having trouble passing a variable called userId to the next page in my application. Below is the snippet of code I am using to pass the value to the next page: $.each($.parseJSON(data), function(key, value) { var userId = value.id_user; ...

How to use a variable as a jQuery selector

My webpage includes a dropdown/select menu that reveals different divs based on the user's selection. Each div contains another dropdown/select menu that I want to trigger an action when changed. The issue is that the ID of these divs is generated dy ...

Is there a way to focus on a specific iteration of the ngFor loop in Angular 9 using jQuery?

I'm working on a list of items inside a modal that uses *ngFor with checkboxes. The goal is to cross out the contents of an item when its checkbox is clicked. Here's the initial code using jQuery in home.component.ts: $('body').on(&apo ...

Guide on implementing v-for on a 2D array

I am facing an issue while trying to iterate through a two-dimensional array using Vue.js. When I attempt to use a nested v-for inside another v-for, I encounter the following error: invalid v-for alias "case" in expression: v-for="case in line" ...

Struggling to retrieve JSON data from within an array

[ { "May": [ { "year": 1994, "date": "2" }, { "Sequence": 2, "Type": "Images" } ], "_id": "1122" } ] The issue I am facing is retrieving the id except for the "date" f ...

Exploring the performance capabilities of web applications using Visual Studio and JavaScript

Currently, I am in the process of conducting a web performance test on a webpage, and my goal is to calculate the time elapsed from when I click on a button to when the desired next page is fully rendered. The challenge lies in the fact that there is a si ...

Ways to incorporate various styles on a mobile screen for a javascript-generated function

In my current project, I have implemented a JavaScript function that renders HTML within a module. function generateHTML(bankName) { let content = `<div class="bankName" style=""><strong style="font-size: 28px;font-wei ...

Trouble with punctuation marks causing difficulty in obtaining address information within an Ionic Angular app

I am currently working on a project in Ionic Angular where I need to fetch and display user address details from the backend on an HTML page. The address details consist of three fields: Address line1 (mandatory), Address line2, and Address line3 (non-ma ...

I'm looking for guidance on the syntax of declaring a constant variable with an empty object in JavaScript. Can someone please explain or

Can you explain the meaning of this JavaScript syntax (likely in ES6)? const {} = variablename; I've been diving into React lately and noticed this syntax used in many examples. For instance: const {girls, guys, women, men} = state; ...

Eliminating Duplicated Words/Strings from an Array in C

I'm currently experiencing an issue with the code output. The array is being filled correctly, but there seems to be a problem with how I am removing repeated words. Here's how the array is filled word by word: #include <stdio.h> #include ...

Having trouble choosing elements with angular.element within ng-repeat loop

In my HTML code, I am using an ngRepeat element: <ol id="animationFrame"> <li ng-repeat="animationImage in animationImages" ng-repeat-listener> <img ng-src="{{animationImage.src}}" id="{{animationImage.id}}"> </li> </ol& ...