Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a large array into smaller array based upon given index values,

I have a large array e.g. aa=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]

I have another array which holds the indexes values based upon which large array need to be chunked. e.g. cc=[10,16]

I want that array aa to be chunked into new arrays

dd[] = [from 0 to cc[0]index]

ee[] = [from cc[0]index to cc[next value]index]

EXAMPLE

dd[] = [1,2,3,4,5,6,7,8,9,10]
ee[] = [11,12,13,14,15,16]

and so on until cc[] has indexes

I could not figure out the logic, if anyone can help me please.

like image 250
raju Avatar asked Jan 05 '23 10:01

raju


2 Answers

You could use Array#map and Array#slice for the parts.

var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16],
    indices = [10, 16],
    result = indices.map(function (a, i, aa) {
        return array.slice(aa[i - 1] || 0, a);
    });
    
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
like image 154
Nina Scholz Avatar answered Jan 07 '23 00:01

Nina Scholz


you can use the new and simple array.slice:

    var array=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16];
    var i,j,temparray,chunk = 10;
    for (i=0,j=array.length; i<j; i+=chunk) {
        temparray = array.slice(i,i+chunk);
        console.info(temparray);
    }
like image 42
Shakti Phartiyal Avatar answered Jan 07 '23 01:01

Shakti Phartiyal