Split an array into chunks without mutability

4 replies
  1. japanfever
    japanfever says:

    //japanfever turn now E3839EE383AAE382AAE9B3A9E38388E383ACE383AD
    //Classic Javascript, the faster…
    var new_array2 = [];
    for (var i = 0; i
    acc.concat((i % size) ? [] : [array.slice(i,i+size)]),
    []);
    console.log(new_array3);

    //Modern Javascript, the faster…
    const new_array4 = […Array(Math.ceil(array.length/size))].map((a,i) =>
    array.slice((i*size),(i*size)+size)
    );
    console.log(new_array4);

    //Modern Javascript, the cooler…
    const new_array5 = array.reduce((acc, a, i) =>
    (i % size) ? acc : […acc, array.slice(i,i+size)],
    []);
    console.log(new_array5);

  2. japanfever
    japanfever says:

    Argg… Your blog cut my code again (can’t put the LESS_THAN sign). Your bloh isn’t ready for writing code!!
    I’ll try again:

    //japanfever turn now E3839EE383AAE382AAE9B3A9E38388E383ACE383AD
    //Classic Javascript, the faster…
    var new_array2 = [];
    for (var i = 0; i LESS_THAN array.length; i += size) {
    new_array2.push(array.slice(i,i+size));
    }
    console.log(new_array2);

    //Classic Javascript, the cooler…
    var new_array3 = array.reduce((acc, a, i) =>
    acc.concat((i % size) ? [] : [array.slice(i,i+size)]),
    []);
    console.log(new_array3);

    //Modern Javascript, the faster…
    const new_array4 = […Array(Math.ceil(array.length/size))].map((a,i) =>
    array.slice((i*size),(i*size)+size)
    );
    console.log(new_array4);

    //Modern Javascript, the cooler…
    const new_array5 = array.reduce((acc, a, i) =>
    (i % size) ? acc : […acc, array.slice(i,i+size)],
    []);
    console.log(new_array5);

    • Génesis
      Génesis says:

      Did you try code tags? It’s like HTML tags, LESSTHANcodeGREATERTHAN your code LESSTHAN/codeGREATERTHAN

      a <= b ? return a : return b

    • Génesis
      Génesis says:

      My favorite one is the cooler one :P, as soon as you don’t need to excecute it too much in endless arrays. I came up to the same one but then I decided to use push (it’s easier to figure out what’s going on) better than spread operator and slice, even if we can omit the return and parentesis. Internally I use yours!

      array.reduce((acc, a, i) =>
      i % size ? acc : [...acc, array.slice(i, i + size)],
      []);

Comments are closed.