angry_kiwi angry_kiwi - 1 year ago 66
Javascript Question

JS - Split array in to n group, each group should have random amount of key

I have an array like this

var arr = ['a', 'b', 'c', 'e', 'f', 'g']

I want to split this array into n groups. These group can hold different amount of key, the group can not be empty. They can hold the amount of key up to whatever. the result should vary every time. An example of expected results as follow:

splitting array into 3 groups

['a', 'b'],
['e', 'f', 'g']

another example result of splitting array into 3 groups

['c', 'e', 'f', 'g']

As you can see there will be always n group (in this case 3) and the amount of key of each group varies everytime

Answer Source

You could use a loop and the rest of the array for creating a new one in parts.

The loop generates a number and keeps at least one item to fill the last array.

var arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g'],
    result = [],
    pos = 0,
    count = 0,
    groupsLeft = 3;

while (--groupsLeft) {
    count = Math.floor(Math.random() * (arr.length - count - groupsLeft)) + 1;
    result.push(arr.slice(pos, pos += count));
result.push(arr.slice(pos, arr.length));