javascript - Extract "N" Values from an Array -
objective
"chunky monkey" problem: create new, multi-dimensional array given array ('arr') , number ('size'). new, multi-dimensional array should create array lengths equal 'size' variable.
example #1
chunk(['a', 'b', 'c', 'd'], 2); var answer = []; function chunk(arr,size){ //do }; return answer
expected answer #1
answer = [['a','b'],['c','d']];
example #2
below example when there odd number of elements/sizes - in situation this, expected result have "remainder" group.
chunk(['a', 'b', 'c', 'd'], 3); var answer = []; function chunk(arr,size){ //do }; return answer
expected answer #2
answer = [['a','b','c'],['d']];
my pseudo-code / approach
var final = []; function chunk(arr, size) { //extract number of elements 'arr' = 'size' var extract = function{ //help! [insert logic] }; //add extracted elements 'group' array var group = [extract]; //push 'group' 'final' array multidimensional array final.push(group); //return final' return final; } chunk(['a', 'b', 'c', 'd'], 2);
questions
- i've been looking @ .foreach(), for(in) loops, .slice(), etc. no avail. of approaches result in cycling through array, not "pairing them".
- am over-complicating things? there more direct approach pseudo-code/approach?
you can use recursive function:
function chunk(arr, size) { if(!arr.length) return []; return [arr.slice(0, size)].concat(chunk(arr.slice(size), size)); }
or loop:
function chunk(arr, size) { arr = arr.slice(); var ret = []; while(arr.length) ret.push(arr.splice(0, size)); return ret; }
Comments
Post a Comment