Today a new colleague asked me a question, that is, there is an array like the below, do not know the specific length, want to be a group of every 4, to regroup as a two-dimensional array, very simple requirements only need to use a loop to take the remainder, write a small demo here to the code including comments posted for the new reference , the code is as follows:
varChartarr =[{value:1,name: ' Haha '}, {value:2,name: ' Haha '}, {value:3,name: ' Haha '}, {value:4,name: ' Haha '}, {value:5,name: ' Haha '}, {value:6,name: ' Haha '}, {value:7,name: ' Haha '}, {value:8,name: ' Haha '}, {value:9,name: ' Haha '}, {value:10,name: ' Haha '}, {value:11,name: ' Haha '}, {value:12,name: ' Haha '}, {value:13,name: ' Haha '} ]; varALLDATA = [];//array to be used for processing varCurrdata = [];//the sub-array is used to save the split data //array to be processed by the loop for(vari = 0; i < chartarr.length; i++) { //add Chartarr[i] to a sub-arrayCurrdata.push (Chartarr[i]); Console.log (i)//The remainder of the 4 is asked here, if I is not equal to 0, and can be divisible or consider the case of less than 4 or equal to 4, plus I equals the current array length-1 if((I! = 0 && (i + 1)% 4 = = 0) | | i = = chartarr.length-1) { //Add the Currdata to the alldata.Alldata.push (Currdata); //Empty the currdata here .Currdata = []; } };
is a two-dimensional array that is processed
JS uses loops to split an array into a new array by a specified multiplier