Breaking up an array into smaller chunks with a slight twist

Here's a straightforward question. I have an array, like this:

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

I am looking to divide this array into multiple arrays as follows:

[[1, 2, 3], [3, 4, 5], [5, 6, 7], [7, 8, 9], [9, 10]]

The key point here is that the last element of each chunk should be the first element of the following chunk.

If anyone has suggestions on the optimal approach to achieve this, please share!

Answer №1

this specific method could be the solution you need,

function divideArray(arr, sections){      
    var x,y, result = [];
    sections = sections - 1;
    for (x=0,y=arr.length; x<y; x+=sections) {
        result.push(arr.slice(x,x+sections +1));
    }
    return result;
}

demonstrations

divideArray([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 3); //[[1, 2, 3], [3, 4, 5], [5, 6, 7], [7, 8, 9], [9, 10]]

Answer №2

This solution has been optimized for speed, performing around twice as fast as the original implementation.

function splitArrayIntoChunks(arr, chunkSize) {
    var currentChunk = [], result = [], i, j;

    for (i=0, j=arr.length; i<j; i++) {
        currentChunk.push(arr[i]);        
        if (currentChunk.length === chunkSize) {
            result.push(currentChunk);
            currentChunk = [arr[i]];
        }
    }    

    if (currentChunk.length !== chunkSize) {     
        result.push(currentChunk);
    }
    
    return result;
}

document.write(JSON.stringify(splitArrayIntoChunks([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 3)));

Answer №3

This code snippet appears to be functional and should produce the desired output.

let array = [1, 2, 3, 4, 5, 6, 7, 8];
let element1 = 0, element2 = 0, element3 = 0;
let finalResult = [];
let splitSize = 3;

for(let index = 0; index < array.length; index += (splitSize -1) ) {
    let tempArray = [];
    for(let subIndex = 0; subIndex < splitSize && arr[index+subIndex]; subIndex++) {
        tempArray.push(array[index + subIndex]);
    }

    finalResult.push(tempArray);
}

console.log("[" + finalResult.join("]\n[") + "]");

Answer №4

Is this solution suitable for your needs?

let originalNumbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

let chunkSize = 3;

let newChunkedArray = [];

for (let i = 0; i < originalNumbers.length; chunkSize += 2) {

    let tempChunk = [];

    for (let j = i; j < i+chunkSize; j++) {

        if (typeof originalNumbers[j] !== "undefined") {

            tempChunk.push(originalNumbers[j]);
        } 
    }

newChunkedArray.push(tempChunk);

tempChunk = [];  
} 

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

Is $timeout considered a questionable hack in Angular.js development practices?

Here's a question for you: I recently encountered a situation where I needed to edit the DOM on a Leaflet Map in order to manipulate the appearance of the legend. To workaround an issue where the map wasn't generating fast enough to access the n ...

Analyzing an External File containing JSON formatted columns

As a newcomer to this site, I welcome any feedback on my approach. My current project involves exploring the 6 degrees of Kevin Bacon by utilizing an external CSV file to create an unweighted graph. The goal is to allow users to determine the shortest path ...

Eliminate incorrect or invalid state when resetting a dropdown in an Angular ng-select component

I have integrated the ng-select plugin into my Angular project for handling dropdowns. One specific requirement I have is to reset the second dropdown when the first dropdown is changed. Below is a snippet of the code: <ng-select [items]="branchMo ...

Setting a value to a FormBuilder object in Angular 2 with Typescript

During my use of Reactive form Validation (Model driven validation), I encountered an issue with setting the value to the form object on a Dropdown change. Here is my Formgroup: studentModel: StudentModel; AMform: FormGroup; Name = new FormControl("", Va ...

Using props as classnames in next.js applications

I am currently attempting to create a dynamic header for each page of my app that changes color based on the current page. Here is my approach: <Header className="headerBitcoin"></Header> My goal is to have the same header component ...

Images are failing to render on Next.js

Hello there! I am facing an issue while working on my Next.js + TypeScript application. I need to ensure that all the images in the array passed through props are displayed. My initial approach was to pass the path and retrieve the image directly from the ...

Generate an array using the keys from a dictionary sorted by their corresponding values

I have a dictionary that I need to iterate through in a tableview. I want to create an array with all the keys ordered alphabetically based on the values in the dictionary. How can I achieve this? static let dict = [ "0P0000KBNA": "Länsför ...

Personalized dropdown appearance

During my work on a select box, I discovered that custom styling is not possible. I attempted to use some plugins but did not find one that met my needs. I am seeking a dropdown menu with options in both black and gray, similar to this template but using ...

unusual behavior observed in addEventListener

I have recently delved into learning about the DOM. I have a project in mind where I want to create a website with buttons that, when clicked, play different drum sounds. As part of my experimentation with JavaScript, I wanted to explore the this keyword. ...

Establishing the first display in AngularJS with the Ionic Framework

Is there a better way to set the initial screen in my Ionic framework application based on whether or not the user is logged in? In the angular.module.config section, I currently use this approach: if (window.localStorage.getItem("userKey") != null) $ ...

Extract the year from a string formatted as 1880-01-01T00:00:00.000

Looking to extract the year from an array of dates with format 1880-01-01T00:00:00.000. What's the most efficient method to accomplish this using JavaScript? ...

Discovering how to create a line break within a text area using the $scope feature in Angular

I'm looking to incorporate a text area for chat input that is resizable. I would like to have some pre-filled texts in it, such as: Hi Jhon, Thanks for contacting us.... I want the text to appear on a new line after the existing content in the textar ...

Optional subscripting for arrays in Swift allows for safe and concise

Here is a simple playground code snippet: var array :[Int?] array = [1, 2, 3] array![1] = 4 Encountered an error while running the Playground Playground execution failed: error: :8:1: error: '@lvalue $T6' is not identical to 'Int?' ...

Tried to insert an array into JSON, ended up with an unexpected outcome

My formatting skills are lacking, perhaps due to a weak foundation. Here is the json I'm working with: 'first_name'=>'steve', 'msg'=>'something here','profile_id'=>1 I am trying to add a new ...

using a loop to retrieve values from an object in PHP

I have a unique object that I received after printing $header echo "<pre>"; print_r($header); echo "</pre>"; stdClass Object ( [date] => [Subject] => [message_id] => [toaddress] => [to] => Array ...

What is the simplest method for transferring data to and from a JavaScript server?

I am looking for the most efficient way to exchange small amounts of data (specifically just 1 variable) between an HTML client page and a JavaScript server. Can you suggest a script that I can integrate into my client to facilitate sending and receiving d ...

Encrypting and decrypting data using RSA in TypeScript

Currently, I am utilizing Angular 4 to develop the front end of my application. For authentication, I have integrated OAuth2 on the backend (which is created using Spring in Java), ensuring that only authorized individuals can access my app. However, ther ...

Why does the entire page in Next.JS get updated whenever I switch pages?

Currently, I am utilizing Next.JS to create a single-page application website in React. I have successfully set up routing (https://nextjs.org/docs/routing/dynamic-routes) In addition, I have also configured Layouts (https://nextjs.org/docs/basic-features ...

The issue of double submission persists, with the prevention of the default action

I'm in need of assistance. Within my form, I have two buttons displayed on the page: "Save" and "Publish". Below is the corresponding HTML code: <button type="submit" class="button">Save</button> <button type="button" class="button" n ...

Exploring a serendipitous element within a 2D array, followed by executing various operations on it

I am trying to find a random element within a 2D array and then perform an operation on it. Here's an example: Grid = np.zeros((64,64)) ones = np.ones((32,64)) minus = -1 * ones Grid[0:32,:] = ones[:] Grid[32:64,:] = minus[:] In this case, half of t ...