I am trying to create a function that can group an array of files to be uploaded into 10MB or fewer chunks. for example on a small scale.
Example: [1mb, 1mb, 5mb, 4mb, 9mb]
Expected ouput: [[5mb, 4mb, 1mb], [9mb, 1mb]]
I need the function to iterate through an array of numbers and group them based on a max of 10mb size. I am a bit confused as to what I should be doing to accomplish this.
Thanks
I hope this help you.
var data = [1, 1, 5, 4, 9];
function getGroups(inputes, maxSize) {
inputes.sort((a, b) => b - a); //sort DESC
var result = [];
while (inputes.length) {
var groups = [];
var sum = inputes[0]; // pick first one (the biggest)
groups.push(inputes[0]);
inputes.splice(0, 1); //remove picked item
var j = 0;
while (j < inputes.length && sum < maxSize) {
if (inputes[j] + sum <= maxSize) {
sum += inputes[j];
groups.push(inputes[j]);
inputes.splice(j, 1);
} else {
j++;
}
}
result.push(groups);
}
return result;
}
console.log(getGroups(data , 10));
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.