What is the best way to determine if a value is present in a JavaScript array? If not found, increment by 0.15 until a unique value is obtained, then append it to the end of the array

In my scenario, I am dealing with text input elements that contain the starting time for a person's shift (e.g. 9:00, 9:30, 10:00, etc).

My approach involves iterating through these elements one by one and storing them in an array. If a particular value already exists in the array, I need to increment the time by 15 minutes (0.15) and check again if it exists. This process will continue until a unique value is found and added to the array.

For instance: John - 9:00 Bill - 9:00 Julie - 9:30 Sam - 9:30 Tony - 9:30

times = []

The first time encountered is 9:00, which is not present in times, so it gets added. The updated times array becomes [9]. Next is another 9:00, which does exist, hence 0.15 is added, resulting in 9.15. Since this new value is unique, it is included in the times array as well. This cycle repeats for all elements. If the minute component reaches .60, an hour needs to be incremented by 1. For example, Tony's time would become 10.

Although I could use an if statement to perform this once, how can I iteratively add 15 minutes and repeatedly check multiple times without using numerous if statements?

if( times.contains(value)) {
      times.push(value + 0.15)
 }

If I were to follow the above approach, it would require countless if statements. Is there a more efficient way to continuously check and terminate the loop immediately after adding a unique value?

Answer №1

To solve this problem, one can utilize a Set. By incrementing the value until it is not in the set, you can then perform mapping on the resultant value.

This particular method involves working with a decimal value equivalent to 15 minutes, which corresponds to a quarter of an hour (0.25).

var times = [9, 9, 9.5, 9.5, 9.5],
    adjusted = times.map((s => t => {
        while (s.has(t)) {
            t += 0.25;
        }
        s.add(t);
        return t;
    })(new Set));
    
console.log(adjusted);

Answer №2

One idea that comes to mind is

  1. Collect all the timestamps, including duplicates. e.g. [9:00, 9:00, 9:30, 9:30, 9:30];
  2. Go through the data and if the i'th timestamp equals the (i-1)'th timestamp, add 15 minutes.
times = Arrays.sort(times);
for(let i=1;i<times.length;i++){
  times[i] = times[i]===times[i-1] ? add15min(times[i]) : times[i];
}

Iterations -:

  1. i=1 (times[i] === times[i-1] so increment) -- [9:00, 9:15, 9:30, 9:30, 9:30];
  2. i=2 (times[i] !== times[i-1] so no operation) -- [9:00, 9:15, 9:30, 9:30, 9:30];
  3. i=3 (times[i] === times[i-1] so increment) -- [9:00, 9:15, 9:30, 9:45, 9:30];
  4. i=4 (times[i] === times[i-1] so increment) -- [9:00, 9:15, 9:30, 9:45, 10:00];

    Final timestamp set: [9:00, 9:15, 9:30, 9:45, 10:00];

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

Access the contents of a URL using PHP

I am attempting to create a PHP array from a URL string. Here is my code: $files = urldecode($_POST['files']); // The String error_log($files); // Outputting to see the format parse_str($files); // parsing... error_log($files[0]); // Viewing th ...

How can I utilize the mapv tool created by Baidu in a Node project?

I need assistance converting the following code to a node environment. The code can be found at Here is the code snippet: var map = new BMap.Map(slice.selector, { enableMapClick: false }); // Create Map instance map.centerAndZoom( ...

Information gathered from checkboxes and dropdown menus

When gathering information from my form fields, I know how to capture data from input fields using this code: 'formData' : { 'timestamp' : '<?php echo $timestamp;?>', 'token' : '<?php echo md5(&a ...

Model-View-Controller CORS Policy

I have been facing a similar issue as described in , but unfortunately, the accepted solution did not work for me. The problem I am encountering is with making an ajax request from a client script. The request works perfectly fine locally, but when runnin ...

Input field that has a drop-down menu

Is it possible to implement a drop-down input field like the one shown below on my website using JavaScript? I want it to display when a specific link, image, or button is clicked without disrupting the overall flow of the page. ...

Slower CSS rendering as Javascript finishes its tasks

I am currently dealing with a jQuery plugin that is quite large and complex, but I will not be sharing it here to keep things simple. The issue I am facing is relatively straightforward, so I will focus on the essential code snippets: There is a click eve ...

Looking for assistance with getting 2 functions to run onLoad using Ajax - currently only 1 is operational

In the coding journey, I first implemented shuffle functions for arrays which was successful. Then, I proceeded to define two global variables that would dictate the random order in which images are displayed on the webpage. The variable picOrder was meant ...

How can we load up to 5 alphanumeric characters from the standard input into a char array using C++?

My program crashes when I load more than five characters. How can I protect it from crashing? #include <iostream> #include <cstdlib> using namespace std; int main() { char tab[5]; int tab2[5]; char *wsk = tab; int i = 0; ...

"Effortless integration of JavaScript with PHP for streamlined database access

My current project involves working with a database table containing two fields - one for URLs and the other for descriptive text. These fields will be updated regularly by a separate script. The task at hand is to create a timer that checks the database ...

Can the default position of the scrollbar be set to remain at the bottom?

I have a select option tag with a scrollbar to view the contents in the dropdown. I am looking for a way to automatically position the scroll at the bottom when an item is selected from the dropdown. jquery code $('document').ready(func ...

Streamline Access to Zimbra Server Automatically

Currently, I am creating a webpage with a login feature at www.newpage.com. Here is the code snippet for reference: <form name="login"> Username<input type="text" name="userid"/> Password<input type="password" name="pswrd"/> <input ty ...

Check to see if the item is not already in the cart, and if so, add it and then increase its quantity

Utilizing React context, I have implemented a simple logic to add products to the cart using the useReducer hook for adding items. If we look at the Redux Toolkit implementation, here is my redux logic: const cartItemSlice = createSlice({ name: " ...

Extract data from axios and display it in a Vue template

Having trouble displaying a value inside a div tag in my nuxt app. An error message keeps popping up saying "Cannot read property 'free_funds' of undefined. Still getting the hang of Axios and Nuxt. Could it be that Bootstrap requires JQuery to ...

Package.json file is not included in Typescript

Each time I execute tsc, it converts the files to JS format successfully, except for package.json. I want this file included in my output directory. Currently, my tsconfig.json looks like this: { "exclude": ["node_modules"], "compilerOptions": { " ...

Exploring the process of performing an AJAX JQuery HTTP request using JavaScript and PHP on the server side - any tips?

Greetings! I have developed a web application using HTML, CSS, and JavaScript. To enhance functionality, I have integrated Bootstrap and jQuery into the project. The application comprises both client-side and server-side components. Let's take a look ...

What's the best way to arrange odd numbers in an array in ascending order?

I am struggling with a coding challenge in C# that requires sorting only odd numbers while keeping even numbers in place. For example, if the input is: [5, 3, 2, 8, 1, 4] The expected output should be: [1, 3, 2, 8, 5, 4] This challenge has been quite p ...

importing with a specific name may result in errors, while importing everything with * from does not

Exploring the directory layout of features within my react application: feature1 actions actionTypes.js crud.js component.js container.js reducer.js sagas.js sagas.test.js services.js index.js feature2 ...

CustomJS TextBox callback to adjust range of x-axis: Bokeh

I'm currently working on a web page that features a plot powered by an AjaxDataSource object. However, I am facing a challenge with implementing a TextInput widget that can modify the xrange of this plot. Here is a snippet of my code: source = AjaxDa ...

An array of unique_ptrs pointing to a list of unique_ptrs

After an extensive search, I couldn't find the answer I was looking for with respect to unique_ptr. This is a problem that has stumped me - while I failed to solve it using unique_ptr, I managed to work around it using more traditional methods. My pr ...

Running a <script> tag with an external src attribute in a dynamic manner through the use of eval

Currently, I am utilizing the Genius API to fetch lyrics for a particular song and then embed them within an HTML <div> tag. My interaction with this API is through PHP, employing an AJAX GET request. Upon a successful AJAX request, the following HT ...