“split array menjadi chunks javascript” Kode Jawaban

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]]
Batman

bereaksi array split menjadi bongkahan

const chunkSize = 10;
const arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17];
const groups = arr.map((e, i) => { 
     return i % chunkSize === 0 ? arr.slice(i, i + chunkSize) : null; 
}).filter(e => { return e; });
console.log({arr, groups})
MysteriousButterfly

JavaScript membagi array menjadi chuncks dari

function splitArrayIntoChunksOfLen(arr, len) {
  var chunks = [], i = 0, n = arr.length;
  while (i < n) {
    chunks.push(arr.slice(i, i += len));
  }
  return chunks;
}
var alphabet=['a','b','c','d','e','f'];
var alphabetPairs=splitArrayIntoChunksOfLen(alphabet,2); //split into chunks of two
Grepper

Membagi array menjadi bongkahan

function sliceIntoChunks(arr, chunkSize) {
    const res = [];
    for (let i = 0; i < arr.length; i += chunkSize) {
        const chunk = arr.slice(i, i + chunkSize);
        res.push(chunk);
    }
    return res;
}

const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
console.log(sliceIntoChunks(arr, 3));
someone as lost as you

split array menjadi 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));
Friendly Frog

split array menjadi 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)
    
}
Husnain Syed

Jawaban yang mirip dengan “split array menjadi chunks javascript”

Pertanyaan yang mirip dengan “split array menjadi chunks javascript”

Lebih banyak jawaban terkait untuk “split array menjadi chunks javascript” di JavaScript

Jelajahi jawaban kode populer menurut bahasa

Jelajahi bahasa kode lainnya