Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

javascript array split chunk

const chunk = (arr, size) => arr.reduce((acc, e, i) => (i % size ? acc[acc.length - 1].push(e) : acc.push([e]), acc), []);

// Examples
chunk([1, 2, 3, 4, 5, 6, 7, 8], 3);     // [[1, 2, 3], [4, 5, 6], [7, 8]]
chunk([1, 2, 3, 4, 5, 6, 7, 8], 4);     // [[1, 2, 3, 4], [5, 6, 7, 8]]
Comment

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

PREVIOUS NEXT
Code Example
Javascript :: how to check if a string contains only spaces in javascript 
Javascript :: define reason in discord.js 
Javascript :: javascript remove parentheses 
Javascript :: convert english number to bangla javascript 
Javascript :: javascript uppercase first character of each word 
Javascript :: jquery set attribute stack overflow 
Javascript :: javascript isset 
Javascript :: datatables change width of columns 
Javascript :: stop immediate propagation 
Javascript :: regex remove non numeric 
Javascript :: iseven js 
Javascript :: get value of selected checkbox jquery 
Javascript :: javascript detect ios device 
Javascript :: how to make a div scrollable 
Javascript :: js range 1 to n 
Javascript :: tolowercase javascript 
Javascript :: how to imporrt Browserrouter in react 
Javascript :: javascript length of object 
Javascript :: countup on scroll react only once 
Javascript :: how to open browser for upload with click on element in jquery 
Javascript :: how can i validate an email address in javascript 
Javascript :: javascript get string between two characters 
Javascript :: remove string from array in js 
Javascript :: jquery ajax post form 
Javascript :: change video src in javascript 
Javascript :: vue.js use scss in balise style 
Javascript :: add class queryselector 
Javascript :: angular create project in current directory 
Javascript :: How to make string shorter javascript 
Javascript :: generates a random rgb color number. 
ADD CONTENT
Topic
Content
Source link
Name
8+8 =