Breaking down the results of a SQL query into an array

I'm looking to implement a paging feature for my query results where I display the first 51 records and store the rest in an array for later retrieval. While I can successfully show the initial 51 results on the page, I'm struggling to figure out how to split the remaining records into arrays of 51.

Here's what my code looks like:

var arrayHTML       = [];

for(var key in data){
    if(data.hasOwnProperty(key)) {
        if (totalX >= 51) {
            //Start putting the results into an array. 51 results per array
        }else if (x > 1) {
            x = 0;
            _userName = data[key].fname + ' ' + data[key].lname;

            populateCards(_userName, 
                          data[key].email, 
                          data[key].img, 
                          data[key].school, 
                          data[key].userID, 
                          true,
                          data[key].encoded);
        } else {
            _userName = data[key].fname + ' ' + data[key].lname;

            populateCards(_userName, 
                          data[key].email, 
                          data[key].img, 
                          data[key].school, 
                          data[key].userID, 
                          false, 
                          data[key].encoded);
            x++;
        }

        totalRowCnt = data[key].totalRows;
        _tmpMath = Math.round(totalRowCnt / totalNum);
        total++;
        totalX++;

        console.log('totalX: ' + totalX)
    }
}

Once it reaches the 51 record mark, it enters the if (totalX >= 51) { block where I'm trying to devise a method to split the remaining records into arrays with 51 entries each.

The current code loops until every 3rd record, then inserts a <br/> tag to create rows of 3 records each. This pattern continues until reaching the 51st record, resulting in 17 rows of 3 records each. The true flag adds a <br/> tag at the end of each row, while false skips adding it temporarily.

I would greatly appreciate any assistance!

Answer №1

Below is the JavaScript Code:

Include this function in your code:

// Here is a straightforward pager function that retrieves a portion of the array
// This allows for easy iteration over specific segments of the array
// @param desired page
// @param number of values per segment
// @return sliced array containing the specified segment
//     (an empty array will be returned if the requested page is out of range
//       e.g. when the array only contains less than 51 items and you request page 2)
array_pager = function ( array, page, show ) {
   var start = (page -1) * show; // Calculate the offset
   return array.slice( start, start + show);
}

You can utilize this function as shown below:

// Assuming the array is named 'data'
var currentPage = array_pager( data, 1, 51); // Retrieve page 1 with 51 values

// You can then iterate over it safely
for(var key in currentPage) {
  _userName = currentPage[key].fname + ' ' + currentPage[key].lname;

  populateCards(_userName, 
                currentPage[key].email, 
                currentPage[key].img, 
                currentPage[key].school, 
                currentPage[key].userID, 
                false, 
                currentPage[key].encoded);
}

// For page 2: array_pager( data, 2, 51) ... 
// For 10 items per page: array_pager( data, 1, 10) ... I hope it's clear now

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

Enabling block scrolling on a parent element using jscrollpane functionality

Is it possible to set up a jscrollpane so that the parent pane doesn't scroll when the child scroll has reached its bottom? Currently, when the child scrolling reaches the bottom, the parent also scrolls. I would like the parent to only scroll when th ...

Sending a static two-dimensional struct array to a function by reference

I am struggling to pass a static two-dimensional struct as a reference to a function and need assistance on how to do it correctly. My understanding is that I should pass a pointer to the first element of struct test to initfield(). C knows the size of th ...

cross-domain policy file

Currently, I am attempting to make a web service call from JavaScript using AJAX: $.ajax({ type: "GET", url: "http://[REMOTE-SERVER-IP]:8080/api/service", contentType: "application/jsonp", crossDomain: true, success: successFunc, ...

What method is most effective for combining two JSON files in Angular?

My data includes a json file with a product list that looks like this: [{"id":76, "name":"A", "description":"abc", "price":199, "imageUrl":"image.jpg", "productCategory":[{ "categoryId":5, "category":null },{ "categoryId":6, " ...

Custom pagination for next/previous links in Django REST framework

When it comes to backend operations, I have integrated the PageNumberPagination as the DEFAULT_PAGINATION_CLASS. Since I am utilizing vue.js along with fetch, there is no need for me to include the entire URL structure provided by django-rest-framework: " ...

Leverage the power of lodash or es6 by creating a custom function that accepts an object containing deeply nested properties and outputs a new object containing only specific properties

I have a complex object with unnecessary properties and deeply nested values that I need to filter. My objective is to transform this initial object into a new object containing only the specific fields I require. Here's an illustration of the large ...

Looking to incorporate React Canary in raw HTML? Or perhaps interested in adding react-dom/client into your project?

Due to certain undisclosed reasons, I am developing a React application without the use of bundlers like webpack. Instead, I simply include React and ReactDOM using <script> tags in my index.html, fetching them from a CDN: https://cdnjs.cloudflare.co ...

In Typescript, it is not possible to assign the type 'any' to a string, but I am attempting to assign a value that is

I'm new to TypeScript and currently learning about how types function in this language. Additionally, I'm utilizing MaterialUI for this particular project. The issue I'm encountering involves attempting to assign an any value to a variable ...

Tips for utilizing createTextNode in JSDOM

When attempting to create a UI test for an HTML element using Jasmine and jsdom, I encountered an issue. Within my component, I utilized the createTextNode function to populate the content of the DOM element. Unfortunately, during testing, the document.c ...

The Nodejs express static directory is failing to serve certain files

Hello everyone, I'm currently working on a project using NodeJs, Express, and AngularJS. I've encountered an issue where my page is unable to locate certain JavaScript and CSS files in the public static folder, resulting in a 404 error. Strangely ...

Struggling to grasp the instanceof operator in Javascript?

This article explains the concept of instanceof operator as follows: The instanceof operator checks if an object has in its prototype chain the prototype property of a constructor. All was well until I stumbled upon this code snippet from Eloquent Ja ...

Having issues with the right margin in HTML5 canvas and struggling to remove the scroll bar

I am struggling with adjusting the margins of my canvas to ensure equal spacing on both sides without any horizontal scroll bars. Desired Outcome: Equal margin on both sides of canvas without any horizontal scroll bars. Issue: The margin-right property i ...

Tactile interactions on iPhone

My goal is to create an off-canvas menu that can be opened with touch events in a systematic way. It functions perfectly in my browser when I click and drag on the body to reveal the menu. However, it encounters a problem on the iPhone. The error message ...

Switch up the placement of the boxes by moving them in different directions, such as

I've been attempting to recreate the button movement demonstrated in this link , but I'm having trouble achieving it. Using CSS animation, I can make the buttons move in a straight line, here's what I have so far: <div id="box" style=&ap ...

Determine the total number of orders made by each customer every month, including instances where no orders were placed

Hey SQL gurus, I could really use some help with this. I have a situation where I have an orders table and a customer table connected by customerid, and I'm trying to achieve two things but I'm hitting a roadblock: I want to display the number ...

Adding information to a MySQL database using PHP/AJAX, triggering the success function only once the data has been successfully inserted (Callback)

I've been struggling to create a basic website, and some of the information provided here is confusing and irrelevant to my specific situation. My website features a form with three input fields, a button, and a list. When the submit button is clicke ...

Issue with Retrieving a particular table from SQL Server using mssql in javascript ('dbo.index')

I am currently experiencing an issue with trying to access a table named dbo.Index from SQL Server in my node js express application. Unfortunately, whenever I attempt to do so, the operation fails and returns no data. Below is the code snippet in questio ...

Ways to shift pictures sequentially in a horizontal line?

I am currently working on a project in asp.net where I need to rearrange 'x' number of images in a row. To explain the scenario, let's say we have 5 images labeled as 1, 2, 3, 4, and 5. Initially, they are in the order of 1, 2, 3, 4, 5. Then ...

From a simple list to a hierarchical structure

I'm currently facing a challenge in transforming an array called "flat" into a tree-like array structure. The initial array looks like this: $folders = array( array('Name' => 'Archive', 'Value' => 'Archiv ...

Using JavaScript, divide a string containing elements of unknown length that may be adjacent based on their type

If I have a string representing an SVG path like: "M72 0v754h405v-86h-311v-211h302v-86h-302v-285h311v-86h-405z" My goal is to transform it into an array where each element consists of either a letter or a positive/negative number. For example: [ ...