我是编程新手,我有一个任务要求从1d数组创建一个2d数组。我想到了这个(没有任何外部来源的帮助,因为它带走了学习经验(。它适用于我们的教授测试输入,我只是想知道这是一个丑陋/低效的解决方案。
function twoDArray(arr, lenSubArray) {
var newArr = [];
var placeHolder = 0;
var leftOver = 0;
for (var i = 1; i < arr.length + 1; i++) {
/* if i is a multiple of the specified sub-array size
then add the elements from placeHolder to i
*/
if (i % lenSubArray === 0) {
newArr.push(arr.slice(placeHolder, i));
placeHolder += lenSubArray;
leftOver++; // tells us how many sub-arrays were created
}
}
/* if original array is not divisible by the length of the specified sub-array
then there will be left over values. Retrieve these values and create an
array out of them and add them to the 2d array.
*/
if (!(arr.length % lenSubArray === 0)) {
/* sub-array count multiplied by the length of each
sub-array gives us the right index to retrieve remaining values
*/
leftOver = (leftOver * lenSubArray);
newArr.push(arr.slice(leftOver))
}
return newArr;
}
测试输入:两个DArray([1,2,3,4,5],3(输出为:[[1,2,3],[4,5]]
你太复杂了:
- 创建结果数组
- 将切片从
i
推送到i+lenSubArray
i
乘以lenSubArray
切片足够智能,可以正确处理阵列的末端
function twoDArray(arr, lenSubArray) {
var i = 0, result = [];
while(i < arr.length)
result.push( arr.slice(i, i+=lenSubArray) );
return result;
}
您可以使用Array#reduce
并基于索引构建新的数组。
function twoDArray(array, length) {
return array.reduce(function (r, a, i) {
i % length ? r[r.length - 1].push(a) : r.push([a]);
return r;
}, []);
}
console.log(twoDArray([1, 2, 3, 4, 5], 3));
您不需要对数组进行迭代。您可以使用Array.prototype.slice
函数。
function twoDArray(a, b){
return (Array(Math.ceil(a.length / b)) + '').split(',').map(function(c, d){
return a.slice(b * d, b * (d + 1));
});
}
以下是您如何称之为
var a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
console.log(twoDArray(a, 3));
// Output:
// [
// [1, 2, 3],
// [4, 5, 6],
// [7, 8, 9],
// [10, 11, 12]
// ]