I need to split an array into 3 even arrays. So far I have only found examples of chunking into specified array lengths. For example:
var array = [1,2,3,4,5];
const results = [];
while (array.length) {
results.push(array.splice(0, 3));
}
return results; //returns [1,2,3],[4,5]
So if i had array = [1,2,3,4,5]
(or any other length)
I need to split this into [1,2], [3,4], [5]
Any ideas?
Figure out the size of the chunks by dividing the length by 3:
var array = [1,2,3,4,5]; const results = []; const chunkSize = Math.ceil(array.length / 3); while (array.length) { results.push(array.splice(0, chunkSize)); } console.log(results);
You could slice the array and use a size for adding the wanted lengths.
This approach does not mutate the given data.
var array = [1, 2, 3, 4, 5], results = [], size = Math.ceil(array.length / 3), i = 0; while (i < array.length) results.push(array.slice(i, i += size)); console.log(results);
.as-console-wrapper { max-height: 100%;important: top; 0; }
Try out this in this you need to provide the number of a chunk
const arr = [1,2,3,4,5]; const chunk = (input, nos) => { let size = Math.ceil(input.length/nos); return input.reduce((arr, item, idx) => { return idx % size === 0? [...arr, [item]]: [...arr.slice(0, -1), [...arr.slice(-1)[0], item]]; }, []); }; console.log(chunk(arr, 3));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.