javascript - Better way to turn a one-dimensional array into multi-dimensional array by required group size in JS -
i rather new js , working on problem asked split array (first argument) groups length of size (second argument) , returns them multidimensional array. got problem work right test cases suggested using array `push()` method. tried multiple times , couldn't ever work right. think getting messed arrays being reference. declared new array each element. went more classic deep copy each element @ time. didn't go , try `push()` method again. there has more efficient way this. want write code. love see better versions please. thanks!
function chunk(arr, size) { var group = 0; var counter = 0; var = false; var odd = false; if (arr.length % size === 0) { group = arr.length / size; = true; } else { group = math.ceil(arr.length / size); odd = true; } var newarr = new array(group); (var = 0; < group; i++) { newarr[i] = new array(size); } (i = 0; < group; i++) { (var j = 0; j < size && counter < arr.length; j++) { newarr[i][j] = arr[counter++]; } } return newarr; } chunk(['a', 'b', 'c', 'd'], 2);
using array.prototype.slice
, function can written in shorter way:
function chunk(array, size) { var result = [] (var i=0;i<array.length;i+=size) result.push( array.slice(i,i+size) ) return result }
Comments
Post a Comment