Group array of files by file size to be uploaded

守給你的承諾、 提交于 2021-02-10 15:00:13

问题


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


回答1:


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));


来源:https://stackoverflow.com/questions/62660560/group-array-of-files-by-file-size-to-be-uploaded

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!