Splitting a Js Array into N Arrays

Splitting a JS array into N arrays

You can make the slices "balanced" (subarrays' lengths differ as less as possible) or "even" (all subarrays but the last have the same length):

function chunkify(a, n, balanced) {        if (n < 2)        return [a];
var len = a.length, out = [], i = 0, size;
if (len % n === 0) { size = Math.floor(len / n); while (i < len) { out.push(a.slice(i, i += size)); } }
else if (balanced) { while (i < len) { size = Math.ceil((len - i) / n--); out.push(a.slice(i, i += size)); } }
else {
n--; size = Math.floor(len / n); if (len % size === 0) size--; while (i < size * n) { out.push(a.slice(i, i += size)); } out.push(a.slice(size * n));
}
return out;}

///////////////////////
onload = function () { function $(x) { return document.getElementById(x); }
function calc() { var s = +$('s').value, a = []; while (s--) a.unshift(s); var n = +$('n').value; $('b').textContent = JSON.stringify(chunkify(a, n, true)) $('e').textContent = JSON.stringify(chunkify(a, n, false)) }
$('s').addEventListener('input', calc); $('n').addEventListener('input', calc); calc();}
<p>slice <input type="number" value="20" id="s"> items into<input type="number" value="6" id="n"> chunks:</p><pre id="b"></pre><pre id="e"></pre>

Split Array of items into N Arrays

I'm not 100% sure how this should work on different sized arrays with different group counts, but this works for your 12 digit example:

function chunkArray(arr, chunkCount) {  const chunks = [];  while(arr.length) {    const chunkSize = Math.ceil(arr.length / chunkCount--);    const chunk = arr.slice(0, chunkSize);    chunks.push(chunk);    arr = arr.slice(chunkSize);  }  return chunks;}

var arr = [1,2,3,4,5,6,7,8,9,10,11,12];console.log( chunkArray(arr, 5) )

Split array into chunks

The array.slice() method can extract a slice from the beginning, middle, or end of an array for whatever purposes you require, without changing the original array.

const chunkSize = 10;
for (let i = 0; i < array.length; i += chunkSize) {
const chunk = array.slice(i, i + chunkSize);
// do whatever
}

The last chunk may be smaller than chunkSize. For example when given an array of 12 elements the first chunk will have 10 elements, the second chunk only has 2.

Note that a chunkSize of 0 will cause an infinite loop.

How to split a long array into smaller arrays, with JavaScript

Don't use jquery...use plain javascript

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

var b = a.splice(0,10);

//a is now [11,12,13,14,15];
//b is now [1,2,3,4,5,6,7,8,9,10];

You could loop this to get the behavior you want.

var a = YOUR_ARRAY;
while(a.length) {
console.log(a.splice(0,10));
}

This would give you 10 elements at a time...if you have say 15 elements, you would get 1-10, the 11-15 as you wanted.

Split an array into smaller chunks of arrays with the length provided by size. Need explanation for solution with modulo

Instead of using your (definitely more efficient, and also clearer) approach of taking consecutive slices, this takes the array item by item, storing the next group to be added in a temporary array. The test is basically asking (with a weird negative test) "Is this index not the last one in the group?" If that condition is true, and we're not on the last one for the current group, we simply add to the temporary group. If it's false, and we are on the last one, we add to the temporary group, add the temporary group to our output and create a new temporary group.

With a little refactoring, we can make this cleaner, perhaps something like this:

function chunkArrayInGroups(arr, size) {
const result = []
let temp = []

for (let a = 0; a < arr .length; a ++) {
temp .push (arr [a])
if (a % size === size - 1) {
result .push (temp)
temp = []
}
}

if (temp .length > 0) result .push (temp)

return result
}

But this holds no advantages over your approach, and is definitely less efficient. So I wouldn't consider it.

Here's an alternative that is to my mind cleaner, but also less efficient than yours:

const chunk = (xs, n) => xs .length <= n 
? [[...xs]]
: [xs .slice (0, n)] .concat (chunk (xs .slice (n), n))

This one grabs the first group by slicing it from the beginning of the array, and concatenates the results of recursively calling itself with the remainder of the array. The recursion ends when there are at most n elements remaining, and then we return an array containing only a copy of our input array ([[...x]]). We make the copy because all the other results are copies and not references, and it's better to be consistent.

This is similar to your approach in terms of number of slices and tests, but because of the recursive nature, it will fail for very large arrays and the repeated calls will make it somewhat less efficient. I'm often willing to take that tradeoff for cleaner code, myself, but YMMV.

JavaScript Split array into multiple arrays inside

You could take an array of the wanted ids and an object which stores the index for the result set for a same group.

var data = [{ candidateConfigId: "1", value: "199128700790" }, { candidateConfigId: "2", value: "Yujith" }, { candidateConfigId: "3", value: "Male" }, { candidateConfigId: "4", value: "SE" }, { candidateConfigId: "5", value: "Colombo5" }, { candidateConfigId: "1", value: "199128700792" }, { candidateConfigId: "2", value: "Yujith2" }, { candidateConfigId: "3", value: "Male" }, { candidateConfigId: "4", value: "SE" }, { candidateConfigId: "5", value: "Colombo3" }, { candidateConfigId: "1", value: "199128700793" }, { candidateConfigId: "2", value: "Yujith3" }, { candidateConfigId: "3", value: "Male" }, { candidateConfigId: "4", value: "SE" }, { candidateConfigId: "5", value: "Colombo2" }],
ids = ['1', '2', '3', '4', '5'],
result = data
.reduce((r, o) => {
let index = r.indices[o.candidateConfigId]++;
r.data[index] = r.data[index] || [];
r.data[index].push(o);
return r;
}, { indices: Object.fromEntries(ids.map(k => [k, 0])), data: [] })
.data;

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

how to split an array into equal chunks?

I broke it down into 3 steps.

  1. Compute numChunks, how many chunks you need? E.g. if you have an array of 103 elements and a max size of 10, then you'll need 11 chunks.
  2. Compute minChunkSize, the size of the smaller chunks. E.g. in the above example, the first 7 chunks will have 10 elements, while the other 3 chunks will have 11 elements (710 + 311 = 103).
  3. Compute numSmallChunks, how many small chunks you can have. E.g. 3 in the above example.

Then you just splice the arr accordingly.

let chunk = (arr, maxSize) => {
let numChunks = parseInt((arr.length - 1) / maxSize) + 1;
let minChunkSize = parseInt(arr.length / numChunks);
let numSmallChunks = numChunks * (minChunkSize + 1) - arr.length;

arr = [...arr]; // avoid muckking the input
let arrays = [];
for (let i = 0; i < numChunks; i++)
if (i < numSmallChunks)
arrays.push(arr.splice(0, minChunkSize));
else
arrays.push(arr.splice(0, minChunkSize + 1));

return arrays;
};

let x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
for (let i = 1; i < x.length; i++)
console.log(i, JSON.stringify(chunk(x, i), null, ''));


Related Topics



Leave a reply



Submit