使用谷歌应用程序脚本根据属性的总和在数组中拆分数组



我想将以下示例数组拆分为数组的数组,其中每个子数组的和不应超过3(此处为var sumMax(。

以下是我当前的代码:

function splitArrByDuration(arr, sumMax) {
var sumMax = 3;
var arr = [["a", 2], ["b", 1], ["c", 2], ["d", 1]];
var splittedArr = [];
var temp_subArr = [];
if (arr.length) {
for (var i = 0; n = arr.length, i < n; i++) {
temp_subArr.push(arr[i]);
if (sumAtIndex(temp_subArr, index = 1) > sumMax && arr.length) {
var extraRow_temp_subArr = temp_subArr.splice(temp_subArr.length - 1, 1); //remove last element of "temp_subArr" because with it the sum will be greater than "sumMax"
//Logger.log(extraRow_temp_subArr); 
arr.unshift(extraRow_temp_subArr[0]); //add the extra from temp_subArr to first index of "arr"
//i = i - 1;
splittedArr.push(temp_subArr);
temp_subArr = [];
}
}
}
Logger.log(splittedArr);
}
function sumAtIndex(arr, index = 1) {
var sumIndex = 0;
if (arr.length) {
for (var i = 0; n = arr.length, i < n; i++) {
sumIndex = sumIndex + arr[i][index];
}
}
//Logger.log(sumIndex);
return sumIndex;
}

Logger.log(splittedArr)的结果当前为:[[a,2.0],[b,1.0]]

预期应为[[a,2.0],[b,1.0]],[[c,2.0]、[d,1.0]]

你能帮我得到正确的结果吗?提前感谢

当我看到您的脚本时,可能需要处理i是最后一个索引的情况。那么,当你的展示脚本被修改时,下面的修改如何?

修改的脚本:

function splitArrByDuration(arr, sumMax) {
var sumMax = 3;
var arr = [["a", 2], ["b", 1], ["c", 2], ["d", 1]];
var splittedArr = [];
var temp_subArr = [];
if (arr.length) {
for (var i = 0; n = arr.length, i < n; i++) {
temp_subArr.push(arr[i]);
if (sumAtIndex(temp_subArr, index = 1) > sumMax && arr.length) {
var extraRow_temp_subArr = temp_subArr.splice(temp_subArr.length - 1, 1); //remove last element of "temp_subArr" because with it the sum will be greater than "sumMax"
//Logger.log(extraRow_temp_subArr); 
arr.unshift(extraRow_temp_subArr[0]); //add the extra from temp_subArr to first index of "arr"
//i = i - 1;
splittedArr.push(temp_subArr);
temp_subArr = [];
// Added
} else if (i == arr.length - 1) {
splittedArr.push(temp_subArr);
}
}
}
Logger.log(splittedArr);
}

已添加:

根据您的以下评论,

如果我将var arr更改为var arr=[["a",2],["b",1],["c",2]、["d",1]、["e",4];脚本从未停止运行。

在脚本中,当值为["e", 4]时,arr.unshift(extraRow_temp_subArr[0])会继续增加arr。这样,就产生了无限循环。为了通过修改脚本来达到新的条件,我认为需要添加检查每个元素值的过程。修改后的脚本示例如下。

修改的脚本:

function splitArrByDuration(arr, sumMax) {
var sumMax = 3;
var arr = [["a", 2], ["b", 1], ["c", 2], ["d", 1], ["e", 4]];
var splittedArr = [];
var temp_subArr = [];
if (arr.length) {
for (var i = 0; n = arr.length, i < n; i++) {
temp_subArr.push(arr[i]);
// Added
if (arr[i][1] >= sumMax) {
var t = temp_subArr.pop();
splittedArr.push(temp_subArr);
splittedArr.push([t]);
temp_subArr = [];
} else if (sumAtIndex(temp_subArr, index = 1) > sumMax && arr.length) {
var extraRow_temp_subArr = temp_subArr.splice(temp_subArr.length - 1, 1);
arr.unshift(extraRow_temp_subArr[0]);
splittedArr.push(temp_subArr);
temp_subArr = [];
// Added
} else if (i == arr.length - 1) {
splittedArr.push(temp_subArr);
}
}
}
Logger.log(splittedArr);
}
  • 在这种情况下,得到[[["a",2],["b",1]],[["c",2],["d",1]],[["e",4]]]

最新更新