Analyzing an array through its sub arrays

Imagine we are dealing with an array of varying length and we need to process it in chunks of maximum size 100, aiming to use the fewest number of chunks. For example, if the array's length is 241, we would need to divide it into 3 subarrays: 41, 100, and 100 (or 100, 100, 41).

curr_len = arr.length;
offset = curr_len%100;
doSomethingWithSubArray(arr.slice(offset))

for(j = offset; j <= curr_len; j = j+100){
    doSomethingWithSubArray(arr.slice(j,j+100))
}

There must be more elegant solutions to this problem, perhaps eliminating the need for a special case before the loop. Any suggestions?

Answer №1

The final segment is anticipated to be smaller in size. In that case, the code would appear like this:

for (var i=0; i<arr.length; i+=100)
    doSomethingWithSubArray(arr.slice(i, 100));

This mirrors the functionality of my splitBy method:

Array.prototype.splitBy = function(n) {
/* obtain: number of elements per array
yield: array of n-sized arrays with the elements (last array might have less than n) */
    for (var r=[], i=0; i<this.length; i+=n)
        r.push(this.slice(i, i+n));
    return r;
}

Then you simply write:

arr.splitBy(100).forEach(doSomethingWithSubArray);

Answer №2

Implement the chunk function

function chunkArray(inputArray, size){
    for(let x, i = 0, c = -1, l = inputArray.length, newArr = []; i < l; i++)
        (x = i % size) ? newArr[c][x] = inputArray[i] : newArr[++c] = [inputArray[i]];
    return newArr;
}

console.log(chunkArray([10,20,30,40,50,60,70,80,90,100], 4));

Answer №3

This code utilizes a functional style approach with recursive solutions. It avoids the use of variables, loops, and counts for a clearer implementation.

const splitArray = function(arr, n){
    if (arr.length == 0) return [];
    const head = arr.slice(0, n), rest = arr.slice(n);

    return [head].concat( splitArray(rest, n) );
};

console.log(splitArray([1,2,3,4,5,6,7,8,9,10], 3));​

Answer №4

This is an example of how to use the reduce method in JavaScript:

var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];

var splitArrays = array.reduce(function(arr, cur, i) {
    if (i % 3 === 0) arr.push([]);
    arr[i / 3 | 0].push(cur);
    return arr;
}, []);
//splitArrays looks like:
//[[1,2,3],[4,5,6],[7,8,9],[10,11]]

Here is a more generic function that can split an array into subarrays of a specified length:

function splitArray(array, num) {
    return array.reduce(function(arr, cur, i) {
        if (i % num === 0) arr.push([]);
        arr[i / num | 0].push(cur);
        return arr;
    }, []);
}

Answer №5

Revamp your doSomethingWithSubArray function by allowing it to take a starting index as a parameter and have it return the next unprocessed index. If there is no more work to be done, return null. Implement this as an "iterator" within a while loop. Perform any additional tasks, such as updating the user interface, immediately after calling this "iterator" within the while loop condition.

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 extract a section of a string with AngularJS

Can someone help me figure out how to remove the last part of a string in order to obtain just the main word? For example, turning string(1) into string. Any suggestions would be appreciated! PS. Note that the string might look like this: sringggg(125). ...

Creating nested JSON in Python involves organizing data structure in a hierarchical

I'm facing an issue with constructing a JSON response from my server. My goal is to create a JSON object that contains other JSON objects received as the output of an SQL query. This way, I can send the containing JSON via my websocket server. Here& ...

RxJS: Transforming an Observable array prior to subscribing

I am retrieving data (students through getStudents()) from an API that returns an Observable. Within this result, I need to obtain data from two different tables and merge the information. Below are my simplified interfaces: export interface student Stude ...

Issue occurred while trying to set the value from an API call response in the componentDidMount lifecycle method

There is a boolean variable disableButton: boolean; that needs to be set based on the response received from this API call: async getDocStatus(policy: string): Promise<boolean> { return await ApiService.getData(this.apiUrl + policy + this.myEndpo ...

How can you deactivate all form elements in HTML except for the Submit button?

Is there a method available to automatically deactivate all form elements except the submit button as soon as the form loads? This would entail pre-loading data from the backend onto a JSP page while restricting user access for editing. Users will only be ...

Utilizing a Material UI custom theme in React with Typescript: A step-by-step guide

Upon using the tool , I received a js file and a json file following the paths mentioned on the theme generator page: // src/ui/theme/index.js /* src/ui/theme/theme.json */ The files operate smoothly when left with the .js extension. However, when I attem ...

Transferring data from JavaScript to ASP.NET (via AJAX)

I'm trying to figure out how to pass variables from JavaScript to a textbox. I have a variable in JavaScript but I am unsure how to transfer it to the textbox. I have heard that using AJAX makes it easy, but I don't know how to implement it. I th ...

Using browser's local storage: deleting an entry

I recently came across a straightforward to-do list. Although the inputs are properly stored in local storage, I encountered issues with the "removing item" functionality in JS. Even after removing items from the HTML, they still persist in local storage u ...

Issues encountered when attempting to send a JSON object from Javascript to a Servlet using AJAX

I've been attempting to send a JSON object to a servlet using AJAX, but I'm running into an issue where the object is showing up as null in the servlet. Can't seem to pinpoint the problem in this code. JAVASCRIPT function submitValues(even ...

express.js creating dynamic URLs causing confusion

router.get('/:username', function(req, res, next) { res.render('dashboard'); }); router.get('/', function(req, res, next) { if(req.user) // this has value res.redirect('/'+req.user); }); I'm experi ...

If the image is not found, deactivate the anchor or hyperlink

I am encountering an issue where I have an image tag within an anchor element setup as shown below: <a href='$image'><img alt='No Image' src='$image'></a> When the image is not available, I can still intera ...

Displaying the error message "No results found" in PHP AJAX live search with multiple values is not possible

I recently went through a tutorial on Most of it worked smoothly after setting it up on my local machine. However, I encountered an issue when searching for data not present in my database. I expected to receive an error message stating "No result found o ...

Adjusting the size of the snap increments

When using gridstack, I have the ability to resize my widgets. However, I've noticed that when dragging on the widgets' handles, they snap to specific sizes, which seems to be a fixed amount. If I wanted to set the widget's size to something ...

React and Redux: The Search for Missing Props

I am embarking on a new project using a different technology stack for the first time. In my previous job, I inherited an existing project with everything already set up. However, I am facing issues as my props are coming up as undefined and I am unsure wh ...

Achieving different results by modifying an array within a forEach loop

I am currently working on a forEach() function that increments an array by one for each iteration. The problem I am facing is that whenever I try to display the value of the number variable in the browser's console, it only shows me the final state i ...

magnific popup: trigger the display by clicking on an element other than the image

A recent request from the client calls for the image caption to cover the thumbnail fully when hovered over. To meet this requirement, I now need to enable clicking on the caption to open Magnific Popup rather than using the <a> tag. Here is what I h ...

Experiencing an issue in Test Cafe when attempting to click on an invisible link using the Client Function

I need to find a way to click on an invisible button in HTML. I attempted to use ClientFunction, however I encountered an error related to the element. import { Selector,ClientFunction } from 'testcafe'; fixture('Clicking Invisible link&apo ...

You must add the module-alias/register to each file in order to use path aliases in

I am currently utilizing typescript v3.6.4 and have the following snippet in my tsconfig.json: "compilerOptions": { "moduleResolution": "node", "baseUrl": "./src", "paths": { "@config/*": ["config/*"], "@config": ["config"], ...

modification of class into hooks, receiving error message 'then' property is not found in type '(dispatch: any) => Promise<void>'

As a newcomer to React hooks, I have been converting code from class components to hooks. However, I am encountering an error message when trying to use 'then' in hooks that says 'Property 'then' does not exist on type '(dispa ...

How do I use onclick to hide a <div> and reveal the content beneath it?

Is there a way for me to hide this <div> when the user clicks outside of it? I want the content behind it to be visible once the <div> is hidden. <html> <style> .overlay { position: fixed; top: 0; left: 0; height: ...