简体   繁体   中英

how to split array into given number in javascript

I have an array and i have to split it into given number and last splited array should accommodate remaining elements if (remaining array size < given_no/2)

for example

var arr = [1,2,3,4,5,6,7,8,9,10,11]

if given_no 2 = Math.round(arr.length/2)= chunk_size 6 = [[1,2,3,4,5,6],[6,7,8,9,10]] 
if given_no 3 = Math.round(arr.length/3)= chunk_size 4 = [[1,2,3,4],[5,6,7,8],[9,10,11]]
if given_no 4 = Math.round(arr.length/4)= chunk_size 3 = [[1,2,3],[4,5,6],[7,8,9],[10,11]]

First of all Math.round(arr.length/2) will return 6 not 5. Please see below code. I have created splitArr function which will return split array based on given number.

 var arr = [1,2,3,4,5,6,7,8,9,10,11]; console.log('Given 2: ' + JSON.stringify(splitArr(arr, 2))); // given 2 console.log('Given 3: ' + JSON.stringify(splitArr(arr, 3))); // given 3 console.log('Given 4: ' + JSON.stringify(splitArr(arr, 4))); // given 4 console.log('Given 5: ' + JSON.stringify(splitArr(arr, 5))); // given 5 console.log('Given 6: ' + JSON.stringify(splitArr(arr, 6))); // given 6 function splitArr(arr, given) { var arrSize = arr.length var split = Math.round(arrSize/given); var returnArr = []; var loopCount; for(i = 0; i < given; i++){ loopCount = (i*split)+split; loopCount = loopCount > arrSize? arrSize: loopCount; var innerArr = arr.slice((i*split), loopCount) returnArr.push(innerArr); } if(loopCount < arr.length){ innerArr.push(...arr.slice(loopCount, arrSize)); } return returnArr; }

You can use Math.round() and array.slice() .

 var splitArray = (arr, num) => { let result = []; let size = Math.round(arr.length/num); for (let i=0; i<num; i++) { let end = i === num-1? arr.length: (i+1) * size; result.push(arr.slice(i*size, end)); } return result; } var arr = [1,2,3,4,5,6,7,8,9,10,11]; console.log(JSON.stringify(splitArray(arr, 2))); console.log(JSON.stringify(splitArray(arr, 3))); console.log(JSON.stringify(splitArray(arr, 4))); console.log(JSON.stringify(splitArray(arr, 5)));

 function splitintochunks(arr,l){
    let result=[];
    while(arr.length>0){
    result.push(arr.splice(0,l));
    }
    return result;
}
//EXAMPLE: call in the below way spltIntoChunks([1,2,3,4,5,6,7,8,9,10,11],5);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM