Split the massive array object into more manageable chunks

I have a large array that can range from 1 to 600K records. To work with this big array, I need to break it into smaller chunks to carry out operations.

How can I achieve this effectively?

Here is my proposed solution: The challenge I am facing is not knowing the exact number of elements in the array, making it difficult to determine the chunk size by dividing it into ten parts.

for(let i = 0; i < largeArray.length; i += largeArray.length/10) {
   var chunk = largeArray.slice(i, what_is_the_chunk_size);
}

Answer №1

If you're looking to split an array into chunks based on a specific size, this function is just what you need. It will create an array of arrays with each chunk containing the specified number of elements.

function splitArrayIntoChunks(array, chunkSize) {
  const size = chunkSize || 10;

  const chunkedArray = array.reduce((acc, item) => {
    let group = acc.pop();

    if (group.length === size) {
      acc.push(group);
      group = [];
    }

    group.push(item);

    acc.push(group);
    return acc;
  }, [[]]);

  return chunkedArray;
}

Answer №2

Does this code look familiar?

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

const source = from(array);

const result = source.pipe(
  skip(10 * i),
  take(10)
);

Answer №3

Utilize the method Array.prototype.reduce. You can even expand that prototype to divide by a specific 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);

Answer №4

I personally prefer this option because of its simplicity and cleanliness.

Originally sourced from this link

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]); // Perform operations
     }   
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The Angular 2 view will remain unchanged until the user interacts with a different input box

I am currently working on implementing form validation using Reactive Forms in Angular 2. Here is the scenario: There are two input fields Here are image examples for step 1 and step 2: https://i.stack.imgur.com/nZlkk.png https://i.stack.imgur.com/jNIFj ...

Angular2 components or module npm packages offer a wide range of functionality and

Looking to develop an npm package containing my Angular2 components. Should I create an angular module and export it, or is exporting just the components sufficient? What advantages does each method offer? Providing examples would be greatly appreciated ...

The category has been defined but remains inaccessible. What could be the reason for this limitation?

I've been utilizing this bson library along with the corresponding declaration found here. Within this library, there is a method called serialize():Buffer which returns a Buffer. When I execute the following code: let data:Buffer = this.serializer.s ...

Connecting the Telegram web app to Angular is a simple process that involves integrating the

I'm having trouble figuring out how to integrate telegram with angular. In my HTML file, I've included the following - <script src="./assets/telegram-web-app.js"></script> However, I'm unsure of what steps to take in t ...

Navigating through an array's contents with RxJs

Is there a more efficient way to iterate over an array fetched from an observable using RxJS operators in order to generate and emit new individual ListingItem objects? onGetItemData(){ this.dataService.getItemData().subscribe((itemData) => { this.it ...

The Angular application is not functioning properly after running npm start, even though all the necessary packages have

Encountering a perplexing issue with my Angular application. After checking out the code on my new machine, I attempted to run my existing Angular 12 project. However, despite the application running properly in the command prompt, it is not functioning as ...

What is the reason for Google Chrome extension popup HTML automatically adding background.js and content.js files?

While using webpack 5 to bundle my Google Chrome extension, I encountered an issue with the output popup HTML. It seems to include references to background.js and content.js even though I did not specify these references anywhere in the configuration file. ...

Convert checkbox choices to strings stored in an array within an object

I have a intricate object structure JSON{ alpha{ array1[ obj1{}, obj2{} ] } } In addition to array1, I need to include another array: array2 that will only consist of strin ...

Is it possible to convert several XLIFF files of different languages into JSON files using Angular?

I was looking to create a universal logic in a single XLIFF build that would allow access to all languages through JSON files. My goal was to find a way for the code to efficiently load multiple translations within one XLIFF build and execute these transl ...

Tips for organizing MUI Card effectively within a React application using TypeScript

Struggling to build a React card component with Material-UI (MUI) and TypeScript that represents a car? The card should contain text, an image, checkboxes, a rating, and a button. Here's the code I've come up with so far: import React from ' ...

What is the best way to invoke a function using a string as its name?

In my grid configuration function, I am assigning column definitions. One key, valueGetter, requires a function to be called to fetch the column value. The issue I am encountering is that the API returns this value as a string. When I try to set it using ...

Issues with implementing AddEventListener in InAppBrowser on IONIC 2

I am currently working on implementing AddeventListener to listen for 'Exit' and 'LoadStart' events in InAppBrowser within IONIC2. Here is my HTML: <button (click)="browsersystem('https://www.google.com')" > Visit URL& ...

Issues with toggling the menu on Angular 14 using Bootstrap 4.6

I am struggling with implementing a menu on the header section of my Angular 14 homepage. The menu I added is not opening as expected. Even after trying various working menu samples from the internet, I couldn't get it to work in my project. Here are ...

Is there a more concise method for accepting a collection of interfaces in TypeScript?

Issue I am facing a simplified version of a problem with my model: Here is how my model currently looks: interface Instrument { name: string; // ...more properties shared by all instruments... } interface Guitar extends Instrument { type: &q ...

Revamping the static method signature of a class in Typescript

One of the modules I'm using is called some-module and it defines a class like this: export declare class Some<T> { ... static create<T>(): Some<T>; map<U>(x: U): Some<U>; } export default Some In my project, I ...

Struggling with object type casting in Typescript

Having issues with casting objects from an HTTP API response to Typescript. I am trying to cast the json data to a Typescript object using the "as" keyword or <Type >, but it's not working as expected. r.forEach(entry => { entry.creatio ...

Adjust the height, width, and color of the "kendo-switch" widget

I am looking to customize the height, width, and color of the "kendo-switch" component. I attempted to modify the element's style directly, but it did not have the desired effect. What would be the most effective approach for achieving this customiza ...

Is there a way to determine if two distinct selectors are targeting the same element on a webpage?

Consider the webpage shown below <div id="something"> <div id="selected"> </div> </div> Within playwright, I am using two selectors as follows.. selectorA = "#something >> div >> nth=1&q ...

Encountering issues with Socket.io: consistently experiencing websocket connection failures along with persistent 404 errors on the

I am facing issues with setting up a websocket using socket.io. The server-side seems to be making a GET call successfully, but on the client-side, I am getting a 404 error: GET http://localhost:6543/socket.io/?uuid=258c4ab9-b263-47ca-ab64-83fe99ea03d4& ...

What is the process for including a unique attribute for child elements within a React component using TypeScript?

I have a component that creates a Table of Contents (TOC) and List for the child elements. These children can be any JSX.Element. Here is an example... <SectionScrollList> <View key="first"/> <View key="second"/> ...