我有一个数组的数组,即 [[3, 6, 7, 7, 4], [5, 9], [4, 1, 6], [6, 3, 6], [ 5,7,8,9]]
。我希望根据时间间隔组合这些数组。例如,如果间隔为2,我想将这些数组中的前两个数组合并为一个数组,然后将接下来的两个数组合并为下一个数组,然后将第三个两个数组合并为下一个数组,依此类推。
我一直在使用concat
,只是不知道如何完成我所追求的目标。非常感谢任何帮助,提前致谢!
最佳答案
如果使用 forEach
或 reduce
迭代外部数组,则可以通过将索引除以间隔将其附加到新结果数组的相应内部数组:
let arr = [
[3, 6, 7, 7, 4],
[5, 9],
[4, 1, 6],
[6, 3, 6],
[5, 7, 8, 9]
]
// combine using forEach
function combine(a, interval) {
const res = [];
a.forEach((subA, ii) => {
const i = Math.floor(ii / interval); // index of combined array in outer array
res[i] = (res[i] || []).concat(subA); // (create if not existant yet,) append
});
return res;
}
// combine using reduce
function combineR(a, interval) {
return a.reduce((res, subA, ii) => {
const i = Math.floor(ii / interval); // index of combined array in outer array
res[i] = (res[i] || []).concat(subA); // (create if not existant yet,) append
return res;
}, []);
}
console.log(combineR(arr, 3));
关于javascript - 根据设定的间隔组合数组(javascript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58384686/