JS uses loops to split an array into a new array by a specified multiplier

Source: Internet
Author: User
Tags array length

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.