1

My example:

let arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18];

let slice = (source, index) => source.slice(index, index + 4);

let length = arr.length;

let index = 0;

let result = [];

while (index < length) {
  let temp = slice(arr, index);
  
  result.push(temp);
  
  index += 4;
}

console.log(result);

Logging:

[[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16],[17,18]]

I want to slice the array to multiple parts for per 4 items [1,2,3,4] [5,6,7,8]...

The code is working fine.

I have 2 questions:

1/. Is there another way to do that via using inline code? Ex: result = arr.slice(...)

2/. After I define:

let push = result.push;

why cannot I still use:

push(temp)

Error message:

Uncaught TypeError: Array.prototype.push called on null or undefined

UPDATE: I've updated the solution based on the answers. Hope it's helpful.

let arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18];

let result = [];

arr.forEach((x,y,z) => !(y % 4) ? result.push(z.slice(y, y + 4)) : '');

console.log(result);

Logging:

[[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16],[17,18]]

1
  • 3
    let push = result.push; extracts the function so that it's no longer associated with any certain object. You would need to use push.call(result, temp) Commented Feb 21, 2017 at 15:54

3 Answers 3

3

A simple way to do it

var chunckArray = function(array, chunkCount){
     var chunks = [];
     while(array.length){
         chunks.push(array.splice(0, chunkCount);
     }
     return chunks;
}

A non consumative way :

var chunckArray = function(array, chunkCount){
     var chunks = [],  i, j;
     for (i = 0, j = array.length; i<j; i+= chunkCount) {
         chunks.push(array.slice(i, i + chunkCount); 
     }
     return chunks;
}
Sign up to request clarification or add additional context in comments.

2 Comments

It would be worth shallow cloning it to keep the desired behaviour and not mutate the original
You are right buddy
2

You can also do it using a for loop which will give you a same result:

let arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18];

console.log(arr.length);
var result=[];

for(var i = 0; i < arr.length; i+=4) {
  result=arr.slice(i, i+4);
  console.log(result);
}

Comments

1

I've done this using a simple reduce (see plnkr):

let arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18];

var counter = -1;
var result = arr.reduce((final, curr, i) => {
  if (i % 4 === 0) {
    final.push([curr])
    counter++;
  } else {
    final[counter].push(curr);
  }

  return final;
}, []);

console.log(result);

You can tweak the 4 and substitute it with a variable chuckSize this will allow you to be able reapply to other things - you could also wrap this in a function with paramerters (array, chunkSize) if you wanted to

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.