Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split array into chunks of N length [duplicate]

How to split an array (which has 10 items) into 4 chunks, which contain a maximum of n items.

var a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']; //a function splits it to four arrays. console.log(b, c, d, e); 

And it prints:

['a', 'b', 'c'] ['d', 'e', 'f'] ['j', 'h', 'i'] ['j'] 

The above assumes n = 3, however, the value should be dynamic.

Thanks

like image 724
mrdaliri Avatar asked Jul 03 '12 20:07

mrdaliri


People also ask

What function split an array into chunks?

Example 2: Split Array Using splice() In the above program, the while loop is used with the splice() method to split an array into smaller chunks of an array. In the splice() method, The first argument specifies the index where you want to split an item.

How do you separate an array?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.


1 Answers

It could be something like that:

var a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'];  var arrays = [], size = 3;      while (a.length > 0)   arrays.push(a.splice(0, size));  console.log(arrays);

See splice Array's method.

An alternative method that does not mutate the array, beside create a shallow copy of it before chunk it, could be done by using slice and a for…loop:

var a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'];  var arrays = [], size = 3;      for (let i = 0; i < a.length; i += size)    arrays.push(a.slice(i, i + size));  console.log(arrays);

While a more functional programming oriented approach, could be:

const chunks = (a, size) =>     Array.from(         new Array(Math.ceil(a.length / size)),         (_, i) => a.slice(i * size, i * size + size)     );  let a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'];  console.log(chunks(a, 3)); console.log(chunks(a, 2));

See Array.from and how new Array(n) works, specifically.

like image 50
ZER0 Avatar answered Oct 01 '22 20:10

ZER0