Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

split array into chunks javascript

Array.prototype.chunk = function(size) {
    let result = [];
    
    while(this.length) {
        result.push(this.splice(0, size));
    }
        
    return result;
}

const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log(arr.chunk(2));
Comment

split array into chunks javascript

const splitArray=(arr, chunk)=>{
    const elementInEachSubArray = Math.floor(arr.length / chunk)
    const remainingElement = arr.length - (elementInEachSubArray * chunk)
    let splitArray = Array.from({length: chunk}, ()=>[])
    splitArray = splitArray.map(
        (array, i)=>{
            return arr.slice(i*elementInEachSubArray, elementInEachSubArray * (i + 1))
}
    ).map((array, i)=>[...array, arr[arr.length - remainingElement + i]].filter(Boolean))
    console.log(splitArray)
    
}
Comment

divide array in chunks

function* generateChunks(array, size) {
    let start = 0;
    while (start < array.length) {
        yield array.slice(start, start + size);
        start += size;
    }
}

function getChunks(array, size) {
    return [...generateChunks(array, size)];
}

console.log(getChunks([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 3)) // [ [ 0, 1, 2 ], [ 3, 4, 5 ], [ 6, 7, 8 ], [ 9 ] ]
Comment

PREVIOUS NEXT
Code Example
Javascript :: wait until foreach is done javascript 
Javascript :: battery percentage js 
Javascript :: javascript hwo to return largest value with index 
Javascript :: js get mouseclick 
Javascript :: align left text in reactstrap 
Javascript :: unix time to date javascript 
Javascript :: set port nextjs 
Javascript :: click element via javascript chrome inspector console 
Javascript :: clz32() js 
Javascript :: get first 10 items of array javascript 
Javascript :: javascript innerhtml table 
Javascript :: material ui multiline 
Javascript :: javascript Validating the Phone Number 
Javascript :: discord.js v13 ending play after 
Javascript :: javascript remove element by id 
Javascript :: setinterval nodejs 
Javascript :: Code to Unsubscribe all youtube channels. 
Javascript :: express request path 
Javascript :: javascript sort array of objects by date 
Javascript :: express ejs 
Javascript :: image next src url 
Javascript :: js colored console log 
Javascript :: json nuget package manager 
Javascript :: react router dom 
Javascript :: npm react-dom 
Javascript :: javascript string get last two character 
Javascript :: unique array javascript es6 Map 
Javascript :: data binding on checkbox angular 
Javascript :: how to ask input in javascript 
Javascript :: localstorage is not defined 
ADD CONTENT
Topic
Content
Source link
Name
8+4 =