caleb15 - 7 months ago 39

Javascript Question

Im new to programming, I have an assignment that asks to create a 2d-array from a 1d array. I came up with this (no help from any outside sources because it takes away the learning experience). It works for our professors test inputs, I was just wondering is this an ugly/inefficient solution.

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

}

Test input: twoDArray([1, 2, 3, 4, 5], 3)

output would be: [[1, 2, 3], [4, 5]]

Answer

you're way too complicated:

- create a result-array
- push slices from
`i`

to`i+lenSubArray`

- increment
`i`

by`lenSubArray`

and slice is smart enough to properly handle the end of the Array

```
function twoDArray(arr, lenSubArray) {
var i = 0, result = [];
while(i < arr.length)
result.push( arr.slice(i, i+=lenSubArray) );
return result;
}
```