Freecodecamp:chunky Monkey

Source: Internet
Author: User

Tag: log Specifies codec push res war CTI Bre free

Requirements:

Monkeys eat bananas but break into several sections to eat Oh!

Divides an array of arr into a number of array blocks, as specified by the size of the arrays.

For example: Chunk ([1,2,3,4],2) =[[1,2],[3,4]];

Chunk ([1,2,3,4,5],2) =[[1,2],[3,4],[5]];

Results:

Chunk (["A", "B", "C", "D"], 2) should return [["A", "B"], ["C", "D"]].
Chunk ([0, 1, 2, 3, 4, 5], 3) should return [[0, 1, 2], [3, 4, 5]].
Chunk ([0, 1, 2, 3, 4, 5], 2) should return [[0, 1], [2, 3], [4, 5]].
Chunk ([0, 1, 2, 3, 4, 5], 4) should return [[0, 1, 2, 3], [4, 5]].
Chunk ([0, 1, 2, 3, 4, 5, 6], 3) should return [[0, 1, 2], [3, 4, 5], [6]].
Chunk ([0, 1, 2, 3, 4, 5, 6, 7, 8], 4) should return [[0, 1, 2, 3], [4, 5, 6, 7], [8]].

Code:

Method 1:

1 functionChunk (arr, size) {2   //Break it up3   vartemp = [];4   varresult = [];5 6    for(varA = 0; A < Arr.length; a++) {7     if(A% size!== size-1)8 Temp.push (Arr[a]);9     Else {Ten Temp.push (Arr[a]); One Result.push (temp); Atemp = []; -     } -   } the  -   if(temp.length!== 0) - Result.push (temp); -   returnresult; +}

Method Two:

1 functionChunk (arr, size) {2   //Break it up3   //It ' s already broken:(4arr =Arr.slice ();5   varARR2 = [];6    for(vari = 0, len = arr.length; i < Len; i+=size) {7Arr2.push (Arr.slice (0, size));8arr =arr.slice (size);9   }Ten   returnarr2; One}

Method Three:

1 functionChunk (arr, size) {2   //Break it up.3   varNEWARR = [];4   vari = 0;5 6    while(I <arr.length) {7Newarr.push (Arr.slice (i, i+size));8i + =size;9   }Ten   returnNEWARR; One } AChunk (["A", "B", "C", "D"], 2);

Method Four:

1 functionChunk (arr, size) {2   //Break it up3   varNewarr=[];4   5    for(vari=0;i<arr.length;i+=size) {6Newarr.push (Arr.slice (i,i+size));7   }8   returnNewarr;9 }Ten  OneChunk (["A", "B", "C", "D"], 2);

Freecodecamp:chunky Monkey

Related Article

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.