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

Does the json_encode() method have any constraints on memory usage?

I'm facing an issue while trying to display a json-encoded array containing another array. The code I have is as follows: <?php include_once('confi.php'); header('Content-type: application/json'); if ($_SERVER['REQUEST_M ...

Transform the JSON data to generate a fresh JSON output

I'm seeking help to develop a script that generates JSON data based on specific conditions. As of now, I believe my logic is correct. Any assistance would be greatly appreciated. CURRENT ISSUES: [resolved]I am unable to determine why the duration ...

Sending a parameter as text from .NET code-behind to a JavaScript function

So here's the situation: I have a gridview that is displayed in a new window separate from the parent window. This gridview contains multiple records, each with a "view" button that allows users to see more details about the record within the same new ...

Access a SQL database to retrieve a data value and seamlessly integrate it into an HTML document with the help of node

I am new to web development and currently facing a challenge in displaying SQL content on an HTML page. My stack includes Node.js, Express, and SQLite3. I have a folder named public containing HTML, CSS, and JS files. The objective is to retrieve a varia ...

Calendar: Display upcoming dates within the next week starting from the current week

Hey there! I have a calendar that includes next and previous buttons. When the user clicks on the next button, the schedule for the upcoming week will be displayed. However, if the user clicks again, nothing happens. My goal is to only show dates for the n ...

Inserting a file read using Node.js into a MongoDB database

Recently, I came across a text file that contains the following data: title: A, alert: notice, desc: Starting title: B, alert: notice, desc: Process Step 1 and 2 Step 1 - Execute Step 2 - Log title: C, alert: notice, desc: "Ending" My goal is to insert ...

Refreshing and enhancing Android contacts through the Expo project

For my current project, I am utilizing the Expo Contact module to automatically update contact information. Here is a part of my script that focuses on updating a selected phone number: const updateContact = async (callId, newCall) => { getSingleConta ...

React TypeScript - creating a component with a defined interface and extra properties

I'm completely new to Typescript and I am having trouble with rendering a component and passing in an onClick function. How can I properly pass in an onClick function to the CarItem? It seems like it's treating onMenuClick as a property of ICar, ...

The functionality of AJAX is hindered in the browser when attempting to fetch data from a URL

Lately, I've been encountering a strange issue when trying to fetch data from a URL. $.ajax({ url: 'URLHERE', dataType: 'html', success: function(data) { //function 2 var xml = $.parseXML(data) $(xml).find('StopLoca ...

What is the best way to execute two JavaScript functions within an inline onclick event?

I am currently working on the following code snippet: <script> function delay (URL) { setTimeout( function() { window.location = URL }, 2000); }</script> And then I have the following within the <body> element: <img src="small_rabbi ...

Challenge in backward compatibility when converting from .on() to .live()

Struggling to make hammer.js work with an outdated 1.6 jQuery in my CMS. The function "on()" isn't available, so I have to use "live()". Here are the two instances: 1. var hammertime = new Hammer(element[0], { drag_lock_to_axis: true }); hammertime. ...

I am struggling to retrieve the data from the Giphy API after making the initial AJAX request

I'm currently in the process of building a basic website that fetches random gifs from the Giphy API. This project is purely for practice, so I'm keeping the site very minimalistic. However, I've hit a snag when it comes to extracting data u ...

Is there a newer alternative to the jQuery UI Draggable component available?

In search of draggable/sortable functionality for my .NET Razor Pages application. Came across the jQuery UI Draggable/Sortable component which I've used years ago with success. However, it's mentioned on the download page that the component is ...

What is the best way to retrieve the JSON data from a POST request made through AJAX to a PHP file and save it in an array variable?

My ajax request sends JSON data to a PHP file named 'receive.php'. user_name , user_id, etc. are defined at the beginning of my script but can be changed to anything else. Below is the JavaScript code I am using: const data = { name: user_na ...

Updating React state using a form input

Seeking assistance on retrieving form values and storing them in state. Despite following various guides (mostly in class style react), I keep encountering the same error: "Nothing was returned from render. This usually means a return statement is m ...

The React onChange event fails to trigger

Why isn't the onChange event firing in the input tag? I used LinkedStateMixin to track the input value before, but now I want to add an onChange event to run a function. After removing LinkedStateMixin, the onChange event still doesn't fire. I ev ...

What is the process for transforming a multidimensional array into a single-dimensional array?

I have an array in a specific format: Array ( [0] => Array ( [PRODUCT_ID] => 40 ) [1] => Array ( [QUANTITY] => 2 ) [2] => Array ( [PIECE_BAG] => 3 ) [3] => Array ( [TOTAL_QUANTITY] => 2 ) [4] => Array ( [UNIT_PRICE] => 3 ) [ ...

Issues persist with Ajax form submissions; the submitted data never seems to go through

I have encountered variations of this issue multiple times, but despite analyzing numerous examples, I am unable to determine why my code is not functioning properly. <script> $('document').ready(function(){ $('datafixForm' ...

`Is there a way to modify the attribute text of a JSON in jQuery?`

I'm attempting to modify the property name / attribute name of my JSON object. I attempted it like this but nothing seems to change. After reviewing the input JSON, I need to convert it to look like the output JSON below. function adjustData(data){ ...

NextJs application displaying empty homepage and preventing redirection

After successfully deploying my nextjs app on netlify, I encountered a strange issue. When I visit the base url of my website, instead of seeing the homepage, all I get is a blank screen. Oddly enough, if I navigate to specific pages on my site, they load ...