Divide an array into smaller arrays

If I create a function named sliceArrayIntoGroups that takes an array and a size as parameters, how can I divide the input array into smaller arrays of the specified size?

function sliceArrayIntoGroups(arr, size) {
  var slicedArray = arr.slice(0, size);

  return slicedArray;
}

For example, if I call this function with ["a", "b", "c", "d"] and 2 as arguments:

sliceArrayIntoGroups(["a", "b", "c", "d"], 2);

The expected output is:

[["a","b"],["c","d"]]

However, I am unsure how to store the remainder of the original array after it has been sliced.

Any assistance on this matter would be greatly appreciated.

Answer №1

A method to divide an array into groups using a standard while loop and a custom step parameter:

function splitArrayIntoGroups(arr, size) {
  var step = 0, splitArr = [], length = arr.length;
  while (step < length) {
    splitArr.push(arr.slice(step, step += size));
  }
  return splitArr;
}

console.log(splitArrayIntoGroups(["apple", "banana", "cherry", "date"], 2));
console.log(splitArrayIntoGroups(["apple", "banana", "cherry", "date", "eggplant", "fig"], 2));
console.log(splitArrayIntoGroups(["apple", "banana", "cherry", "date", "eggplant", "fig"], 3));

The step parameter determines the offset for each extracted slice.

Answer №2

Here is a handy little recursive function that can help you split an array into groups of a specified size. It works by slicing off n elements from the start of the array and then calling itself with the remaining elements.

function sliceArrayIntoGroups(arr, size) {
  if (arr.length === 0) { return arr; }
  return [ arr.slice(0, size), ...sliceArrayIntoGroups(arr.slice(size), size) ];
}

console.log(sliceArrayIntoGroups([1,2,3,4,5], 2));
console.log(sliceArrayIntoGroups([1,2,3,4,5], 3));
console.log(sliceArrayIntoGroups([1,2,3,4,5], 10));

Answer №3

Check out this code snippet that splits an array into two pieces and then combines them into one:

function splitArray(arr, size) {
  if (size >= arr.length || size <= 0) { return arr; }
  return [arr.slice(0, size), arr.slice(size)];
}
console.log(splitArray(["apple", "banana", "cherry", "date"], 2));

Answer №4

Give this a try:

 function divideArrayIntoGroups(arr, size) {
   var result = [];

   while (arr.length > 0) {
     result.push(arr.splice(0, size));
   }

   return result;
 }


 console.log(divideArrayIntoGroups(["a", "b", "c", "d", "e", "f"], 3));
 console.log(divideArrayIntoGroups(["a", "b", "c", "d"], 2));

function divideArrayIntoGroups(arr, size) {
  var result = [];

  while (arr.length > 0) {
    result.push(arr.splice(0, size));
  }

  return result;
}

This function will split the array into smaller groups based on the value of the size parameter, so

divideArrayIntoGroups(["a", "b", "c", "d", "e", "f"], 3);

will produce the following output:

[["a", "b", "c"], ["d", "e", "f"]]

Answer №5

The slice() method in JavaScript is a useful tool for extracting specific elements from an array and creating a new array with those elements. By utilizing a for loop, we can segment the original array into smaller arrays of a specified size and store them in a larger array called arrGroup.

function divideArrayIntoGroups(originalArr, groupSize) {
  let arrGroup =[];
  for (let i=0; i<originalArr.length; i+=groupSize) {
    let smallArray = originalArr.slice(i,i+groupSize); // Create a smaller array of desired size
    arrGroup.push(smallArray);
  }
  return arrGroup;
}

Answer №6

Minimize:

let numbers = [1,2,3,4,5,6,7,8,9];
let chunkArray = function(array, size) {
    let temp;
    return array.reduce(function(carry, item, index) {

        // Check if we're at a chunk point: index % size == 0
        if (!(index % size)) { 

            // If temp currently holds items, push it onto carry
            if (temp && temp.length) { 
                carry.push(temp); 
            }

            // Reset temp to an empty array
            temp = []; 
        }

        // Push the current item onto temp
        temp.push(item);

        // If this is the last item in the array, push temp onto carry
        index === array.length - 1 && carry.push(temp);

        return carry;
    }, []);
};

chunkArray(numbers,5);

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

What steps do I need to take in order to activate the server-side console logging?

Recently, I created some server middleware in my api/index.js file: module.exports = function(req, res, next){ console.log(req); next(); }; After that, I integrated it into my nuxt.config.js: serverMiddleware: [{path: 'stocks', handler ...

Using React Native to trigger a function based on a conditional statement

<Pressable onPress={()=> { if(newID) { EditPress(newID) } else { AddPress } }} style={styles.logBox} > <Text style={{ textAlign:"center", ...

I'm having trouble managing state properly in Safari because of issues with the useState hook

Encountering Safari compatibility issues when updating a component's state. Though aware of Safari's stricter mode compared to Chrome, the bug persists. The problem arises with the inputs: https://i.sstatic.net/WSOJr.png Whenever an option is ...

`Grab the attention of a specific span of text using AngularJS`

What I have is a code that currently highlights words in a list based on a predefined array. $scope.arrayFilter=["is","mom","beautifull",'beer']; However, I no longer need this code. I only want to highlight text within the ".marque" class from ...

Is GridHelper in three.js creating a non-traditional grid?

I recently discovered that the standard normal vector for geometries in three.js is typically considered to be (0, 0, 1). However, when I tried using the GridHelper constructor, I noticed that it actually creates a plane defined by the X and Z axes, resul ...

Vue.js is updating state, yet the view remains static and does not re-render

My experience with learning Vue.js has been great, but I keep encountering a problem where setting a data property based on state doesn't update the component when the state changes. For instance... Check out these code snippets <router-link v-i ...

Sorting JSON content to obtain particular outcomes

I am utilizing the Quotes on Design API https://quotesondesign.com/api-v4-0/ to display random quotes by various designers on my website. However, I am looking to showcase quotes by specific designers in a random manner. Unfortunately, the code snippet ...

Make sure to validate onsubmit and submit the form using ajax - it's crucial

Seeking assistance for validating a form and sending it with AJAX. Validation without the use of ''onsubmit="return validateForm(this);"'' is not functioning properly. However, when the form is correct, it still sends the form (page r ...

What methods are available to generate dynamic shapes using HTML?

Looking to create an interactive triangle where users can move vertices or sides, updating angles in real-time. I'm struggling with how to accomplish this task. My initial attempt was to manually draw the triangle using the code below. <!DOCTYPE ht ...

Using a Javascript while loop to iterate through an array and display the elements in the .innerHTML property

As a newcomer to Javascript, I am in the process of teaching myself. My current task is to develop a function that will display each element of the array AmericanCars with a space between them. I have successfully been able to show an individual element u ...

In certain cases, golang's byte and string types may be interoperable, whereas

This code snippet showcases Golang usage package test import ( "fmt" "testing" ) func TestOne(t *testing.T) { bytes := make([]byte, 0) bytes = append(bytes, 1, 2, 3) // successful bytes = append(bytes, ...

Updating a component when a prop changes

Embarking on my journey into the world of React, I find myself in need of assistance. The issue at hand involves re-rendering data within my Table component. Whenever a new API call is made to create an entry in my database using Prisma, the newly added d ...

Implement Vue.js functionality to dynamically add the 'active' class upon clicking an element, while also removing

Is it possible to create an active link on a div element? Check out this example to see how you can achieve that in your code: http://jsfiddle.net/fiddleyetu/9ff79/ $(function() { $( 'ul.nav li' ).on( 'click', function() { $ ...

Instead of receiving my custom JSON error message, Express is showing the server's default HTML error page when returning errors

I have set up a REST api on an Express server, with a React app for the front-end. The design includes sending JSON to the front-end in case of errors, which can be used to display error messages such as modals on the client side. Below is an example from ...

The command 'node' is not being recognized as either an internal or external command, potentially due to it being an operable program or batch file. This issue only arises when attempting to

Whenever I try to npm install a package or check the node/npm version, it works fine. However, upon attempting to start the app with any scripts, I encounter the following error message. [EDITED] $ npm start > <a href="/cdn-cgi/l/email-protection" ...

Guide to using JavaScript to populate the dropdown list in ASP

On my aspx page, I have an ASP list box that I need to manually populate using external JavaScript. How can I access the list box in JavaScript without using jQuery? I am adding the JavaScript to the aspx page dynamically and not using any include or impor ...

Navigating views with ReactJS using ES5

I have been searching for ReactJs guides, but most of them are based in ES5. As a result, I have begun using ReactJS in this manner. Now that I understand how to create all my components, I am ready to build a small single-page-application. However, I am s ...

Choose the key value from a deep object structure

I'm facing a dilemma. Within the layers of this object, I need to identify and select a specific key among the nested elements. The structure of the object is as follows: var x={ "_shards": { "total": 10, "successful": 5, ...

Tips for resolving the strange behavior on a webpage with multiple active buttons labeled "portfolio"

I'm currently dealing with an issue regarding the behavior of a particular webpage that is quite unusual. I have provided a link to the Github page where this issue is occurring. Interestingly, the problem seems to be resolved when I remove the nav ta ...

Comparing the Length of JavaScript Arrays

I have code that checks for similar values in two arrays, and if there are any, they are not displayed in the result. However, when I switch the lengths of the arrays so that Array2 is longer than Array1, I end up with an empty result array. How can I achi ...