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

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

I have another array that contains index values ​​based on how large the array needs to be split. egcc=[10,16]

I want aa array to be tagged in new arrays

dd [] = [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[]it has indexes

I could not understand the logic if anyone could help me.

+4
source share
3 answers

You can use Array#mapand Array#slicefor 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; }
Run codeHide result
+6

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);
    }
Hide result
+2

You can do something similar if you do not want to use the built-in methods.

function createChunks(aa, cc) {
    var temp = [], chunks = [];
    for(var i=0, j=0, k=0; i<aa.length; i++) {
        if(aa[i] == cc[j]) {
            temp[k] = aa[i];
            chunks.push(temp);
            temp = []; k=0; j++;
        }
        else
            temp[k++] = aa[i];
    }
    return chunks;
}


var aa=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16], cc=[10, 16];

var chunks = createChunks(aa, cc);
console.log(JSON.stringify(chunks));
Run codeHide result
+1
source

Source: https://habr.com/ru/post/1671221/


All Articles