如何将数组转换为 JavaScript 中的复杂数组?
假设我们要写一个函数,它接受一个数字数组和数字 n,其中 n >= 数组中的任意数字。如果数组中连续元素的总和超过数字 n,则该函数需要将数组拆分成子数组。
例如 −
// if the original array is: const arr = [2, 1, 2, 1, 1, 1, 1, 1]; // and the number n is 4 // then the output array should be: const output = [ [ 2, 1 ], [ 2, 1, 1 ], [ 1, 1, 1 ] ];
让我们编写此函数的代码 −
示例
const arr = [2, 1, 2, 1, 1, 1, 1, 1];
const splitArray = (arr, num) => {
return arr.reduce((acc, val, ind) => {
let { sum, res } = acc;
if(ind === 0){
return {sum: val, res:[[val]]};
};
if(sum + val <= num){
res[res.length-1].push(val);
sum +=val;
}else{
res.push([val]);
sum = val;
};
return { sum, res };
}, {
sum: 0,
res: []
}).res;
};
console.log(splitArray(arr, 4));
console.log(splitArray(arr, 5));输出
控制台中的输出将是 −
[ [ 2, 1 ], [ 2, 1, 1 ], [ 1, 1, 1 ] ] [ [ 2, 1, 2 ], [ 1, 1, 1, 1, 1 ] ]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP