Separate the Array elements and organize them into an object

Check out this code snippet that demonstrates how to divide an array into chunks. If you have a more efficient solution, please share it with me.

var numbers = [];
for (var i = 0; i < 4500; i++) {
    numbers.push(i);
}
var chunks = {};
var start = 0;
var end = 999;
if (numbers.length > 999) {
    for (var i = 0; i < 4; i++) {
        chunks[i] = numbers.slice(start, end);
        start = end + 1;
        end = start + 999;
        console.log(start + ":" + end);
    }
}
console.log(numbers.length);
console.log(chunks[1].length);

Answer №1

If you no longer require the array, consider using Array#splice() instead of Array#slice().

let arr = [],
    obj = {},
    index;
    
for (index = 0; index < 4500; index++) {
    arr.push(index);
}

index = 0;
while (arr.length) {
    obj[index++] = arr.splice(0, 1000);
}

document.write('<pre> ' + JSON.stringify(arr, null, 4) + '</pre>');
document.write('<pre> ' + JSON.stringify(obj, null, 4) + '</pre>');

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 while loop is missing a value assignment for an integer

I am attempting to retrieve page number values from the method getPageNumber(), where the page number is being printed in the console. However, that value is not being used in the While loop. Even when I try to print pageNum, it returns a promise. Refer to ...

ng-view scope interacting with parent scope connection

Excuse the late-night desperation, but I have a question about my AngularJS application that uses ngRoute. Currently, everything is being handled in one controller. The issue arises with a form in a view where I need to take the input field data and store ...

Efficiently accessing and displaying nested models in AngularJS

Currently, I am in the process of developing a website that involves numerous relational links between data. For instance, users have the ability to create bookings, which will include a booker and a bookee, as well as an array of messages that can be asso ...

Extracting information from HTML and transferring it to Javascript using jQuery

My goal is to utilize jsGrid for showcasing database data without repeating code extensively. I aim to generate separate grids for each <div> with a specific id while passing on relevant values accordingly. To clarify my objective, here's a sni ...

sending an array from one CodeIgniter view to another view via Ajax

In the following code segments of my application, myArray is an array where each element contains a few objects that I need to use in a second view. When I use alert(myJSON);, I am able to see the array in the alert window. However, when the view loads, i ...

Updating the head() properties in Nuxt.js via asyncData() is not possible

After creating a server-side rendered Vue.js blog with Nuxt.js using Typescript and Ghost, I encountered a problem updating html metatags with data from asyncData(). According to the Nuxt.js documentation, asyncData() is triggered before loading page comp ...

Is it possible for a Java method to organize an array using a parameter with a reference to an object variable?

Recently delving into Java, I am endeavoring to create a Method for a class project that arranges an array based on an object variable reference provided as the argument. For instance, if the object variable reference 'name' is given, it should s ...

Using axios.spread() allows for caching of my API requests, a feature that is not available when

Thank you for taking the time to read this. I find myself in a peculiar situation where I am required to invoke multiple CMS API routes from my server to incorporate their response.data into an object that will later be transferred to the client side. The ...

Validating Two DateTime Pickers as a Group with Javascript in asp.net

How to Ensure Group Validation of Two DateTime Pickers Using JavaScript in ASP.NET ...

PostBackUrl="javascript:void(0);" prevent postback from occurring for all controls within the webpage

Is there a way to prevent postback for a specific control on the page? I've managed to achieve this successfully. However, after clicking on that control, all other controls on the page do not trigger any postbacks. Everything was working fine until I ...

Is there a way to access the original query string without it being automatically altered by the browser?

I'm currently encountering an issue with query strings. When I send an activation link via email, the link contains a query string including a user activation token. Here's an example of the link: http://localhost:3000/#/activation?activation_cod ...

Is it feasible to add on to an existing object in the database? (Using Node.js and Mongoose

After saving an object to the database using the following code: var newObject = new PObject({ value : 'before', id : 123456 }); newObject.save(function(err) { if (err) ...

In Typescript, define a class with a property that will serve as the name of another type's property

Trying to define a class property for another type: class TypeOne { public static readonly code: string = 'code'; } class TypeTwo { public [TypeOne.code]: TypeOne } Encountering an error message: The computed property name in the class pr ...

Ways to activate the enter key

Here we have the input bar and search button setup in our HTML code: <div> <div class="input-group search-bar"> <input type="text" class="form-control search-box" placeholder="Search people" autofocus="" ng-model="searchPeople"& ...

JavaScript increase numbers in an array

We are dealing with a numerical array where each element has its maximum value. How can we update the elements in order for the array to transition from [0, 0, 0] to [x, y, z]? For example, if the maximum array values are [2, 1, 2] and the initial array i ...

The clear text button is malfunctioning and not resetting the search input as intended

I'm currently working on a filterable search form that displays images in a grid based on the search input. Everything is working smoothly - the grid resets when I delete text from the search input field. However, I've encountered an issue with t ...

Styling CSS for disabled nested elements

In a project I am currently working on, I've noticed that disabled items do not appear disabled enough. My initial plan was to easily address this issue with some CSS. Typically, adjusting the opacity is my go-to solution to achieve the desired effec ...

Load blender scene with functional lighting using THREE.JS GLTFLoader

Recently, I've been experimenting with the GLTFLoader feature in THREE.js along with the new blender exporter found here. After successfully adding a model with similar color material and importing the scene into my THREE.js project, I noticed that wh ...

Display JSON Array information in a template using a component

I have made an API call and received the response in this.order.info this.http.get(this.order_info_url+'/'+this.order_id) .subscribe( response => { this.order_info = response.json(); console.log(this.order_info[0]); }, ...

Whenever I repeatedly click the button, the array will store a new value. My goal is for it to collect and store all values obtained from the function

After retrieving data from the listAPI value using an API, the output is displayed as follows: //output - console.log(listAPI) 5) [{…}, {…}, {…}, {…}, {…}] 0: {id: "1", name: "name 1", active: "true"} 1: {id: " ...