1

I have array:

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

Then I want to make group of 4 elements. Every iteration, this array must be modified until it get's final face.

Step 1:

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

Step 2:

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

Step 3:

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

Step 3:

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

How is this possible?

I tried this:

var array = [1,2,3,4,5,6,7,8,9,10,11,12,13,14]
var i,j,temparray,chunk = 4;
for (i=0,j=array.length; i<j; i+=chunk) {
    temparray = array.slice(i,i+chunk);
    console.log(temparray);
}

But I don't know then how to save this chunk into own array and not in the new array.

4
  • 1
    Have you tried anything? Commented Nov 20, 2017 at 17:22
  • Please provide the code you've already tried and we'd be happy to help you get it working. Commented Nov 20, 2017 at 17:22
  • what is with your 4 step approach? now in one (in the accepted answer)? if so, please change the question. Commented Nov 20, 2017 at 18:17
  • @NinaScholz every 4 element must be splitted and saved in one array, so left elements are less than 4 and we must save it to use later. Commented Nov 20, 2017 at 18:20

7 Answers 7

3

Using Array#reduce method.

const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14], 
newArr = arr.reduce((acc, item, index) => {
    if ((index) % 4 === 0) {
        acc.push([item]);
    } else {
        acc[acc.length - 1].push(item);
    }
    return acc;
}, []);

console.log(newArr); // [ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 9, 10, 11, 12 ], [ 13, 14 ] ]

Sign up to request clarification or add additional context in comments.

Comments

3

You could splice the array until the length is smaller than the index of the last insertation.

var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14],
    i = 0;
    
while (i < array.length) {
    array.splice(i, 0, array.splice(i, 4));
    console.log(JSON.stringify(array));
    i++;
}

Comments

2

lodash probably has better performances than my implementation, but if you are looking to do so with vanilla javascript then you can like this (though many other ways are possible):

var arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14];

var newArr = arr.reduce((acc, val, idx)=>{
	if(idx % 4 === 0){
  	acc.push([]);
  }
  acc[acc.length-1].push(val)
  return acc
}, [])

console.log(newArr);

3 Comments

VanillaJS beats everything!
I was sure lodash would make it faster than my code, but after several checks on jsfiddle I was 3-5 times faster than lodash!!! :)
VanillaJS only beats everything if you have the skills and experience to write faster and safer code that the author of a well-tested and widely used library.
1

The lodash method chunk will do this for you.

result = _.chunk(arr, 4);

Comments

1
function chunkArray(myArray, chunk_size){
    var index = 0;
    var arrayLength = myArray.length;
    var tempArray = [];

    for (index = 0; index < arrayLength; index += chunk_size) {
        myChunk = myArray.slice(index, index+chunk_size);
        // Do something if you want with the group
        tempArray.push(myChunk);
    }

    return tempArray;
}
// Split in group of 3 items
var result = chunkArray([1,2,3,4,5,6,7,8], 3);
// Outputs : [ [1,2,3] , [4,5,6] ,[7,8] ]
console.log(result);

1 Comment

Please try to understand the question properly. User is asking to save the array in place and don't want new array.
1

Just push it to the resulting array:

const chunk = 4, result = []
for (var i = 0, j = array.length; i < j; i += chunk) {
   result.push(array.slice(i,i  + chunk));
}

Comments

1

I thought it would be fun too if I add one more solution using recursive calls, Happy coding!

Test it here

function split(arr, offset, res){ 
  
  //stop condition (offset exceeds len of array) 
  if(offset>arr.length) 
	return res; 

  //slice 4 elms 
  res.push(arr.slice(offset,offset+4)); 

  //recursion 
  return split(arr, offset+4, res);
  
}
  
var res = split([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14], 0, []);

console.log(res);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.