javascript - grouping elements dynamically inside arrays -
this question has answer here:
- split array chunks 32 answers
i new javascript. have list of 500 or more items. need split array sub arrays each containing 20 items. i.e 25 arrays if there 500 items , each array containing 20 items. created 25 arrays below:
var firstset=[]; var secondset=[]; .....
and populate each of array using loop. in javascript how can make programmatically since main list can return more 500 items in future , each sub array should configured more 20 items in future. best solution fix situation?
as comments say, should split 2 dimentional array:
var mainarray=[1,2,3,4,5,6,7,8,9,10]; function splitarray(arr,qty){ var mainarr=[], subarr=[]; for(var i=0;i<arr.length;i++){ subarr.push(arr[i]); if( ((i+1) % qty == 0) || i+1==arr.length){ mainarr.push(subarr); subarr=[]; } } return mainarr; } console.log(splitarray(mainarray,2));
this creates 1 array 5 indexes. in each index, have array of 2 elements. groups in [1,2], [3,4], [5,6], [7,8], [9,10]
Comments
Post a Comment