0

I have an Array, which can vary from 1 - 600K records. Therefore, I need to find a way to break this bigger array into smaller chunks and perform some operation of the smaller chunks.

How can I do this?

My solution as follows: My problem is that I am not sure, how many elements the array will contain so I am not able to divide it by 10, to determine the chunk size.

for(const i = 0 ; i < largeArray.length; largeArray.length/10) {
   var p1 = largeArray.slice(i,whatisthechunksize);
}
Prashant Pimpale
  • 10,349
  • 9
  • 44
  • 84
Sharon Watinsan
  • 9,620
  • 31
  • 96
  • 140

4 Answers4

0

You can use this function, it will return an array of chunks considering the total elements of the original array.

function splitArray(array, chunk) {
  const chunkSize = chunk || 10;

  const chunkedArray = array.reduce((acc, item) => {
    // delete the last item from acumulator
    // (it is made until the group get all the chunk items)
    let group = acc.pop();

    // validate if the group has the size defined
    if (group.length === chunkSize) {
      acc.push(group);
      group = [];
    }
    // Insert in the chunk group
    group.push(item);

    // push the group to the reduce accumulator
    acc.push(group);
    return acc;
  }, [[]]); // [[]] is used to initialize the accumulator with an empty array

  return chunkedArray;
}
JuanDM
  • 1,250
  • 10
  • 24
0

Something along these lines?

import { from } from 'rxjs';
import { skip, take } from 'rxjs/operators';

const source = from(array);

const p1 = source.pipe(
  skip(10 * i),
  take(10)
);
Mike Jerred
  • 9,551
  • 5
  • 22
  • 42
0

Use Array.prototype.reduce. You can also extend that prototype to split by the desired number :

Array.prototype.splitBy = function(size) {
  return this.reduce((p, n) => {
    if (p[p.length - 1].length < size) p[p.length - 1].push(n);
    else p.push([n]);
    return p;
  }, [[]]);
}

const data = new Array(500).fill(0).map((v, i) => i);

const splitted = data.splitBy(10);

console.log(splitted);
console.log('Size of splitted array = ', splitted.length);
0

I would go with this! Simple and Clean!

Copied from here

var size = 3; var arrayOfArrays = [1,2,3,4,5,6,7,8,9,10];

for (var i=0; i < arrayOfArrays.length; i+=size ) {
     var chunckedArray = arrayOfArrays.slice(i,i+size);
     console.log(chunckedArray); 

     for(var j = 0; j < chunckedArray.length; j++)
     {
       console.log(chunckedArray[j]); // Do operations
     }   
}
Prashant Pimpale
  • 10,349
  • 9
  • 44
  • 84