“JavaScript split array menjadi bongkahan” 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

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

JavaScript split array menjadi bongkahan

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

Array Chunk JavaScript

let input = [1,2,3,4,5,6,7,8,9];
let chunked = []
let size = 2;

for (let i = 0;  i < input.length; i += size) {
  chunked.push(input.slice(i, i + size))
}
console.log(chunked)
Restu Wahyu Saputra

JS membagi array menjadi array yang lebih kecil

Array.prototype.chunk = function(n) {
  if (!this.length) {
    return [];
  }
  return [this.slice(0, n)].concat(this.slice(n).chunk(n));
};
console.log([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15].chunk(5));
Ever Dev

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

Jawaban yang mirip dengan “JavaScript split array menjadi bongkahan”

Pertanyaan yang mirip dengan “JavaScript split array menjadi bongkahan”

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

Jelajahi jawaban kode populer menurut bahasa

Jelajahi bahasa kode lainnya