JavaScript: Iterate over an array with custom start and end points

I have a massive collection of items — approximately 30000 in total.

     startIndex = Math.floor( Math.random() * arr.length ) 

I am interested in selecting a random subset from the entire collection.

My goal is to iterate through the array starting at startIndex and ending at startIndex + n.

Important note: It is crucial for this array to remain unchanged, as it would be too resource-intensive to re-render the entire dataset.

What approach would be most effective for this task? Should I use a for loop or a while loop?

Answer №1

Instead of initializing var i = 0 at the beginning of your for loop, consider setting it to the starting point and modify the condition from i < array.length to i < ending_index.

This adjustment allows you to iterate through all indexes between the specified start and end_index, replicating the behavior of a traditional for loop that typically starts from 0 and goes until the end of the array.

Answer №2

If you want to handle a large array in batches, give this method a try. You may need to adjust the batch size depending on your needs.

function ProcessLargeArrayInBatches() {
    var largeArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36];

    var batchSize = 10;

    for (var start = 0; start < largeArray.length; start = start + batchSize) {
        ProcessBatch(largeArray, start, GetEndIndex(start, batchSize, largeArray.length));
    }

}

function GetEndIndex(startIndex, batchSize, arrayLength) {
    var endIndex = startIndex + batchSize;

    if (endIndex > arrayLength) {
       return arrayLength;
    }

    return endIndex;
}

function ProcessBatch(someArr, startIndex, endIndex) {
    console.log("Start Batch from " + startIndex + " to " + endIndex);
    for (var i = startIndex; i < endIndex; i++) {
       console.log(someArr[i]);
    }
    console.log("Ending Batch from " + startIndex + " to " + endIndex);
}

Answer №3

let numbers = [5, 6, 7, 8];
let groupSize = 3;
let startingPoint = Math.floor(Math.random() * (numbers.length - groupSize));

for (let j = startingPoint; j < startingPoint + groupSize; j++) {
    // Your custom code goes here
}

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

What is the best way to search for multiple values in AngularJS with ng-repeat?

Within the database, the sales_Use_Taxable field offers three potential options: "Yes", "No", or it may even be null. Utilizing the code snippet below to filter the results, any rows with a null value for this particular field are not displayed. <tr ng ...

Implementing a JavaScript function to a button within an existing form in JSP - Best practices

Currently, I am working on developing multiple JSP pages and I encountered a requirement where I needed to add a function to a button within an already existing form. The challenge was that the form's submit button was configured to navigate to anothe ...

"An error occurred stating that _co.JSON is not defined in

During my attempt to convert an object into a string using the JSON method, I encountered an error upon loading my page: Error: _co.JSON is undefined The stacktrace for this error message is extensive and seems unnecessary to include at this point. Th ...

Unable to adjust the width of a table column within a horizontally scrollable container

I am struggling to resize the columns of a large table with 20 headers. Despite trying to place the table inside a div with overflow:auto, I still cannot achieve horizontal scrolling or make the div expand when resizing the columns. A sample code snippet ...

Is it possible for me to return a function reference as a response to an API call?

Is it possible to return a function reference or function as a response to an API call from an Express server when using AngularJS as the front-end framework? I attempted to send the response object like this: {per: true, listEvnts: events} where events i ...

Sorting through mongoose information on the front end using EJS depending on a dropdown pick

Beginner embarking on my inaugural project here. I have developed 2 Mongoose schematics and models for managing categories and products. The products are nested within the corresponding categories model. Using Node and Express, I successfully sent all ca ...

Refreshing modal content following successful AJAX call

Does anyone know how to fix this issue in my code? I need to reload a modal for another database query after a successful operation if(result === 'success'){ $("#editarModalOcup").modal('hide'); $('#success .modal-body'). ...

Is there a way to prevent users from selecting certain days in ion-datetime?

After searching through the official documentation, I couldn't find a solution. I am in need of a function similar to the jQuery datepicker beforeshowday function. My goal is to disable all weekends (Saturday and Sunday) in upcoming dates so that user ...

Ensure that the array of JSON objects is a subset of another array of JSON objects

I am looking to compare each array in testEdge with newarr and find the matching id for each array in testEdge const testEdge = [ [{ id: '0', from: '0', to: '1' }, { id: '1', from: '1&ap ...

Contrasting actions observed when employing drag functionality with arrays of numbers versus arrays of objects

Being a newcomer to D3 and JavaScript, I'm hoping someone can help me clarify this simple point. I am creating a scatter graph with draggable points using code that closely resembles the solution provided in this Stack Overflow question. When I const ...

Calculate the product of a column with a designated numerical factor using Awk

I recently started using awk more frequently to process the output files from a model I am working with. Currently, I am faced with an issue involving multiplication. My goal is to calculate the relative change in percentage. For example: A B 1 150 0 ...

The value of the Post Form Request Object is currently set as 'object Object'

Just delving into the world of Node.js and I have come across several questions here on SO in relation to this topic. However, the issue I am facing is that the request body always shows as { 'object Object' : ''} Here is the server-si ...

Arrange the child elements of a div to be displayed on top of one another in an HTML document

I am struggling with a div containing code .popupClass { width: 632px; height: 210px; position: absolute; bottom:0; margin-bottom: 60px; } <div class="popupClass"> <div style="margin-left: 90px; width: 184px; hei ...

text box with an immobile header

As the browser window size decreases, the layout changes. However, when scrolling down, the search text box moves up and is no longer visible due to its lack of fixation. How can I make the search text box stay fixed as I scroll down? I tried implementing ...

Tips for utilizing playFromPositionAsync method with expo-av Video in React Native

While working with the Video Expo component, I came across a prop called playFromPositionAsync. In the Video.d.ts file, it is defined like this: export default class Video extends React.Component<VideoProps, VideoState> implements Playback { ... ...

Endless loop caused by Angular UI-router's promise resolving

I'm attempting to retrieve data from my SQLite database before loading a view using resolve when defining the state in ui-router. Currently, this is how I've set up the state: .state("menu", { templateUrl: "templates/menu.html", control ...

Deploy a Node.js websocket application on Azure Cloud platform

After smoothly running on Heroku, the server app encountered a problem with startup after moving to Azure. Below is the code snippet: const PORT = process.env.PORT || 2498; const INDEX = '/index.html'; const server = express() .use((req, res ...

Enhancing User Interfaces with TypeScript Accordions

Looking for a way to expand the sub-menu when the SETTINGS menu is clicked using typescript. Here is the list structure: <li> <a href="#"> <i class="fa fa-cogs fa-fw"></i> <span>SETTINGS</span> </a> ...

Reposition the initial element to the end of an array using setInterval() within a React component

I'm attempting to rearrange the elements in an array in React, specifically by moving the first item to the last position using a setInterval function: const [cardOrder, setCardOrder] = useState([card1, card2, card3, card4]); setInterval(() => { ...

Adjusting Spacing Between Characters

I've been looking for a way to convert regular characters (ABC) to full-width characters (ABC), but I haven't had any luck so far. That's why I'm turning to you guys for help. Currently, I don't have any JavaScript code writt ...