JavaScript - Execute a function when reaching the end of an array

I am currently working on a Node.js program that has a similar structure to the following:

var foo = [val,val,val....]
var bar = []

for(i=0;i<foo.length;i++){
  bar.push(foo[i])
  if(bar.length % 29 == 0){

    //do something with items 1-29 of bar

  bar.length = 0;
  }
}

The foo array contains over 1,000 items and I need to execute a specific function for every set of 29 items within it. I am using the bar array to successfully capture each set of 29 items and reset it once the function is performed. However - I am looking for guidance on how to handle the last remaining items in the foo array that are less than 29.

If anyone has suggestions or tips on how I can approach this issue, it would be greatly appreciated.

Answer №1

let numbers = [1, 2, 3, ...]
for(index = 0; index < numbers.length; index += 29) {
    let subset = numbers.slice(index, index+29);
    // perform some operation on the subset
}

Answer №2

let values = [val, val, val....]
let container = []

for (let j = 0; j < values.length; j++) {
    container.push(values[j])
    if (container.length % 29 == 0 || j == values.length - 1) {

        //perform operations on items 1-29 of the container

        container.length = 0;
    }
}

By including the condition j == values.length - 1, the code will handle the final group of items even if it doesn't consist of exactly 29 elements. If values.length == 28, the operation will occur after processing the 28th item. With values.length == 40, it will trigger at the 29th and 40th items.

Answer №3

For every set of 29 elements in foo, the following code snippet can be implemented:

var foo = [1,2,3....];
var bar = [];
for(i=0;i<foo.length;i++){  
  bar.push(foo[i]);           
  if(bar.length >= 29)  {
    // perform actions on bar
    bar = [];
  }  
}
if(bar.length>0) {
    // perform actions on remaining elements in bar
}

Alternatively, a more elegant approach is to create partitions of size N and execute the same functionality:

var bar, size = 29;
for (var i=0, j=foo.length; i<j; i+=size) {
    bar = foo.slice(i, i+size);
    // perform actions on bar
}

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

Delay the execution of a function until subscription within RxJS and React's setState

One of the interesting features of RxJS is the function called fromCallback. This function takes a callback as its last parameter and returns an Observable. I am intrigued by the idea of combining this with React's setState function to achieve somethi ...

Guide on setting up a Redirect URL with React Router

I am aiming to trigger a redirect URL event using ReactJS. Is there a way to achieve this? I have already attempted the following: successRedirect(){ this.transitionTo('/'); } as well as successRedirect(){ this.router.transitionTo ...

`Thoughts on Difficulty Attaching Child Elements in JavaScript with appendChild`

I am having trouble with appending some HTML that is being received as a string in a div. For some reason, the appendChild method is not working as expected. Here is my JavaScript code: var doc = document.getElementById("products"); var notes = doc.getEle ...

Manipulating arrays according to user input

While working on my project, I encountered an issue that led me to this specific point: #include <stdio.h> void printData(char *data) { for (int i = 0; i < 9; i++) { printf("%c ", data[i]); } printf("\n&quo ...

Show a separate button for every order placed

Hello, I am a beginner in RoR and currently working on building a web application. I have a typical app with Users who create Posts. An additional model called Online is utilized to display the posts on a shared wall, and it is linked with a nested for ...

What happens to CSS specificity when JavaScript is used to change CSS styles?

When JavaScript modifies CSS, what is the specificity of the applied styles? For example: document.getElementById("demo").style.color = "red"; Would this be deemed as inline styling? ...

Running JavaScript on a change function while performing web scraping with Selenium using Java proves to be challenging

Task at hand: 1) Navigate to the following URL: 2) Choose "FO Stocks" from the selection box to display a new table of FO Stocks. 3) Sort the table in descending order by clicking on the "FFM Column" header. Extract the top 5 rows from the table. My a ...

Prevent any future dates from being entered

My Thoughts: <input type="text" class="datepicker" placeholder="DD/MM/YYYY" id="datepicker" ng-model="datepicker" name="datepicker" style="width:100%" tabindex="4" required/>` Controller: `$('#datepicker').datepicker({ format: &a ...

Executing actions based on events in PHP

Is there a way in PHP to trigger event Y when action X is performed? Currently, I am using jQuery Ajax at regular intervals to track the latest updates, but I believe this method puts unnecessary load on the server. Here's what I'm trying to acc ...

Only display the Google map marker when it is within the current view

I'm looking to enhance the animation of my Google map marker. I've successfully customized my map, implemented a unique marker, and enabled the animation feature. However, there are a couple of obstacles preventing it from functioning as desired. ...

Eavesdrop on outbound requests on a web page using JavaScript

As I develop a single-page application that integrates a third-party analytics tool (such as Heap, Segment, Mixpanel, etc.), I am looking to actively monitor the outgoing HTTPS requests from my app and take necessary actions, such as logging. I am curious ...

Retrieve the value associated with the data attribute of the chosen dropdown option

I need to extract the custom data attribute from the chosen option of a dropdown menu and insert it into a text box. This will be the second data attribute I'm working with. I plan to implement code that will run whenever the user changes the option ( ...

The browser mistakenly sends a GET request instead of a POST request

I've created a JavaScript function that sends POST requests similar to an HTML form. The function implementation is as follows: function sendPostRequest(url, data) { var $form = $('<form action="' + withContext(url) + '" method= ...

Trouble with Datatables when displaying data in input fields

I have been working on a project that involves using Datatables and encountered an issue with column export. The column displays successfully on the webpage but fails to display after using render as shown below: this._dataTable = this.$mainTable.DataTa ...

Tips for showing data associated with the chosen option from a dropdown list in Angular.js fetched from an API

My goal is to automatically display the coordinator's name based on the selection in a dropdown list populated with data from an API. The dropdown options are the email addresses from the JSON data below, and upon selecting a login ID, the correspondi ...

Transform Material UI Typography to css-in-js with styled-components

Can Material UI elements be converted to styled-components? <Container component="main" maxWidth="XS"> <Typography component="h1" variant="h5"> Sign in </Typography> I attempted this for typography but noticed that t ...

Locate the nearest neighbor for each given point to find the closest point

We have a method that takes an array of points as input and aims to find, for each point in the array, the closest point to it (excluding itself). Currently, this process involves a brute force approach of comparing every point with every other point. The ...

Creating an asynchronous function in a Vue.js component that utilizes the Lodash library

I'm struggling with writing an async function correctly. Can someone provide guidance on how to achieve this? async search (loading, search, vm) { let vm = this _.debounce(() => { let ApiURL = '/users/' } let { res } = await ...

Leverage the sync function within the await .then("sync") method in JavaScript

If a synchronous function is called within the .then part of an asynchronous await .then, such as: await asyncFunc(...) .then(res => sendMSG(res)) .catch(err => next(err)); function sendMSG(res){ xyz } The sync function sendMSG i ...

Measuring the Frequency of Letters in a Document

I am trying to analyze the frequency of each letter in an input text file. However, every time I run the program, it ends up displaying the filename instead of the actual letters and crashes. Any suggestions on how to fix this issue? Sample Text File Inpu ...