A function that iterates to determine the length of an array and, if it is fewer than 10 elements, appends elements from another array to it until it reaches a length of 10

My goal here is to query a list of available programs for a week-long period. I organize this data into an object where each day's programs are easily accessible through object look-up, creating programsOnSelectedDay.

programDateLookUp {
  "22/04/24": [
    {
      "programType": "CLINIC",
      "start_date": "2022-04-24T16:00:00.000Z"
    }
  ],
  ...
}

To retrieve the programsOnSelectedDay, I use the Object keys like this:

const programsOnSelectedDay = programDateLookUp[selectedDay] || [];
where selectedDay = '22/04/25'
 LOG  programsOnSelectedDay [...]

Now, I need a recursive function to check the length of programsOnSelectedDay, add the next day's programs to the array until there are at least 10 results or all days in the week have been accounted for.

The current implementation reaches maximum recursion depth, so I've come up with a potential solution:

  const addProgramsBasedOnLength = (programs) => {
    if (programs.length === 0) return programs;

    if (programs.length < 10) {
      const nextDay = moment(selectedDate, FORMAT).add(1, 'days').format(FORMAT);
      const nextDayPrograms = programDateLookUp[nextDay] || [];
      return addProgramsBasedOnLength([...programs, ...nextDayPrograms]);
    }
    return programs;
  };

If I only return [...programs,...nextDayPrograms], it works but gives me results for one day only. I'm looking for guidance on how to modify this recursive function to either add up to 10 results to the original programsOnSelectedDay or cover the entire week.

Any suggestions on how to achieve this?

Answer №1

Following a suggestion similar to @Ouroborus comment, I experimented with a strategy.
Instead of iterating through the entire week array containing formatted dates for the currently selected week, I opted to use the index of the date I had already chosen.
This approach specifically adds days of the week that come after the selectedDate without unnecessarily looping through days preceding it.

function adjustProgramsByLength(programs, programDateLookup, selectedDate, week) {
  if (programs.length >= 10) return programs;

  const indexOfSelectedDate = week.findIndex(day => day.formatted === selectedDate);

  const upcomingWeekPrograms = week.slice(indexOfSelectedDate + 1).reduce((accumulator, { formatted }) => [
    ...accumulator,
    ...programDateLookup[formatted] || [],
  ], []);

  return [...programs, { key: 'noMoreResultsForDay' }, ...upcomingWeekPrograms];
};

I included the 'key' object there for displaying purposes when iterating through the resulting array in the UI.

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

how to implement dynamic water fill effects using SVG in an Angular application

Take a look at the code snippet here HTML TypeScript data = [ { name: 'server1', humidity: '50.9' }, { name: 'server2', humidity: '52.9', }, { name: 'server3', humidity: ...

What is the best way to iterate through a collection of two or more arrays in order to determine the total length of all

https://i.stack.imgur.com/PpFlB.pngI currently have multiple Arrays containing various inputs this.listNumber = [ { "GenericQuestions": [ { "input": "long", }, { "input": & ...

Nested ng-repeat in AngularJS allows you to loop through arrays

I am currently facing an issue with updating the choices in my object that contains a question and list of choices. I'm using nested ng-repeats to display this object on the page. While changing the 'question' works perfectly fine, modifying ...

Creating JavaScript Objects from HTML Form data with the help of serializeJSON

Struggling extracting HTML form data into the required JSON format for server communication. Despite following a guide, I can't get the output right. Managed to extract question keys and values, but labeling is tricky. Current Output: {"Question1":" ...

The type of jQuery selector

I came across jQuery code that looks like this return 13 == t.keyCode ? (t.preventDefault(), !1) : void 0 Can someone explain what the ? and : mean in this context? Please provide a reference for further reading, as I am still new to jQuery. Thank you ...

Vue: Develop a master component capable of displaying a sub-component

Is there a way to design a main component that is able to accept and display a subcomponent? Take the following scenario for instance: <Container> <Item/> <Item/> <SubMenu/> <Btn/> </Container> ...

Navigation that sticks and changes upon hovering over div elements

Just delving into the world of jQuery and JS, so I appreciate your patience:) Currently, I have a sticky navigation bar positioned at the top of my webpage that links to different sections of content below. I am looking to create an effect where the corr ...

Error Occurred: Angular View Not Loading

I created a new file named new.html to test navigation, but when I load the page View1.html should appear, instead I see a blank page. Below is the content of my new.html: <!DOCTYPE html> <html data-ng-app="demoApp"> <head> ...

What exactly sets one string apart from another? (JavaScript)

Is it possible to use JavaScript to detect the specific part of strings that makes them different from each other? For example, consider the following three strings: String1 = "Java1String" String2 = "Java2String" String3 = "Java3String" If String1 is t ...

Enhancing UI design with Vue.js

I'm attempting to customize elements using data from a JSON file in Vue.js: <div v-for="(item, index) in json._items" class="help-inner-callout" v-html="item.text" style="top:item.top; left: item.left;">&l ...

AngularJS traditional navigation rather than using $location.path

While working in controller A, I used $location.path('/home') for redirection. However, I realized that I needed a normal redirect as $location.path does not reload the page. I am aware that in ui-route, we have $state.go({reload:true}) for this ...

Conceal a designated H2 identifier through the use of either javascript or CSS

We are currently exploring Zendesk for our customer support website, but we have encountered some limitations in terms of customization. Our goal is to remove specific text from the page by utilizing Zendesk's widgets function, which can be implemente ...

The essence of my design disappears when I generate a canvas object using Fabric.js

After defining top and left attributes for a Canvas Object using a JavaScript function, I encounter an issue when creating a fabric Canvas object. var fabricCanvas = new fabric.Canvas('mycanvas'); Upon creation, my HTML Canvas has its top and ...

How can I extract a list of values from an array containing blittable structs?

I have a set of blittable structures in an array, each of which is of fixed size and stored sequentially in memory. My goal is to extract multiple arrays from this single array of structures. Below is the structure definition: [Serializable] public struct ...

Exploring the concept of looping through an array of JSON objects using AngularJS

I am working with a JSON object and my goal is to extract specific information to be displayed using console.log in the browser. FROM: Frontier WHSE, TO: ENTEC POLYMERS The JSON object structure is as follows: { "loadStops": [{ "id": 1, ...

Utilizing Vue-cli and Three.js to Load STL Files

I'm facing an issue where I can't seem to load an STL file into a three.js scene that is being created via vue-cli. The project setup involves using vue-cli 'vue init webpack ProjectName', 'cd ProjectName', 'npm install ...

Troubleshooting CSS Animation Failure in Internet Explorer 11

My mouse over / mouse out animation works perfectly in Firefox and Chrome, but it's not functioning in IE. Can anyone suggest why this might be happening when it was working fine before? var actual = 1; var over = 0; var over2 = 0; function scrol ...

Ways to save a value in an array only if it is not already stored

I am currently developing a PHP report that is intended to be exported as a CSV file with comma delimiters. Within this report, there are three columns related to product_id, each serving a specific purpose: SKU Parent / Child Parent ...

Within the ASP.NET Framework 4, it is necessary to enable the Listbox control to trigger an event when a user double

Currently, I am developing a project in ASP.NET 4. I have encountered a situation where the regular ListBox in version 4.5 includes an attribute named OnMouseDoubleClick. However, since I am using ASP.Net 4, I am looking for the best approach to replicat ...

Size of Nested Arrays in MongoDatabases

I am a poetry enthusiast and have gathered a collection of beautiful poems. The structure of the documents in my collection is quite interesting: { "_id" : "Romeo and Juliet", "acts" : [ { "title" : "ACT I", "scenes" : [ ...