# Splitting an array into equal chunks and then allot remaining

I have a array where I need to divide equally into person number of chunks.

1. if there are 100 items in array for 10 persons, 10 chunks to be created with each 10 items

2. if there are 100 items in array for 9 persons, 9 chunks to be created and each would get 9 items and the extra should be given to first person, second person and so on. which means Person 1 = 10; Person 2, 3, 4 … would have 9 items

3. if there are 100 items in array for 11 persons, 11 chunks are to be created with each would get 10 and the extra should be given to first person. which means

```Person 1 is 10
Person 2 is 9
Person 3 is 9
Person 4 is 9
Person 5 is 9
Person 6 is 9
Person 7 is 9
Person 8 is 9
Person 9 is 9
Person 10 is 9
Person 11 is 9
```

I have tried with

```Object.defineProperty(Array.prototype, 'chunk', {
value: function(chunkSize) {
var array = this;
return [].concat.apply([],
array.map(function(elem, i) {
return i % chunkSize ? [] : [array.slice(i, i + chunkSize)];
})
);
}
});

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ..., 150, 151].chunk(Math.floor(151 / 31))
```

but that would gives me an incorrect allocation.

Use the remainder of the division to get the number of slices that need an extra element. Then use the index in the new (chunked) array to determine whether it needs that extra element (i.e. when that index is less than the remainder).

NB: I would not alter the Array prototype. Just make this a plain function.

Implementation:

```function partition(arr, length) {
let rest = arr.length % length;
let size = Math.floor(arr.length / length);
let j = 0;
return Array.from({length}, (_, i) => arr.slice(j, j += size + (i < rest)));
}

let data = Array.from({length: 151}, (_,i) => i+1);
let result = partition(data, 31);
console.log(result);```