Breaking down an array into groups - where did I go wrong in my code?

Check out the following code :

function splitArrayIntoGroups(arr, size) {
  // Splitting the array into groups.
  var newArray = [];
  for(var i = 0; i < arr.length; i++){
    for(var j = 0; j < size; j++){
      newArray.push(arr.splice(0, size));
    }
  }
  var finalResult = [];
  for(i = 0; i < newArray.length; i++){
    if(newArray[i].length != 0){
      finalResult.push(newArray[i]);
    }
  }
  return finalResult;
}

splitArrayIntoGroups([0, 1, 2, 3, 4, 5, 6, 7,8], 2);

The expected output is -

[[0, 1], [2, 3], [4, 5], [6, 7], [8]]
. However, it currently returns [[0, 1], [2, 3], [4, 5], [6, 7]]. Interestingly, if the input array is changed to ([0,1,2,3,4,5,6,7,8,9,10],2), the code works as intended.

P.S: The focus here is to identify and rectify the issue in this existing code rather than suggesting an entirely different approach or code snippet.

Answer №1

Essentially, a single loop is all that is required as the array is spliced to extract chunks of the desired size.

This method lends itself well to looping until the array reaches a length of zero, at which point the loop can be exited.

With this approach, the final result is readily available.

function chunkArrayInGroups(arr, size) {
    var newArr = [];
    // for (var i = 0; i < arr.length; i++) {
    while (arr.length) {                        // add this for looping and checking
        // for (var j = 0; j < size; j++) {
        newArr.push(arr.splice(0, size));       // keep this for doing the work!
        // }
    }
    // var result = [];
    // for (i = 0; i < newArr.length; i++) {
    //     if (newArr[i].length != 0) {
    //         result.push(newArr[i]);
    //     }
    // }
    // return result;
    return newArr;                              // return only newArray
}

console.log(chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 2));
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

To achieve the desired outcome, you can use the following code snippet:

let chunkSize = 2;
const originalArray = [0, 1, 2, 3, 4, 5, 6, 7, 8];
const newArray = [];
for (let index = 0; index < originalArray.length; index += chunkSize) {
    newArray.push(originalArray.slice(index, index + chunkSize));
}
console.log(newArray); // Output will be [[0, 1], [2, 3], [4, 5], [6, 7], [8]]

Answer №3

Your issue lies in not accounting for the scenario where the items remaining in the array are fewer than the specified size. In other words, when arr.length < size, the remaining elements are not included in the chunk array.

To address this, I have made updates to your code to ensure it functions correctly:

function chunkArrayInGroups(arr, size) {
  // Break it up.
  var newArr =[];
  while(size<arr.length){
      newArr.push(arr.splice(0, size ));
  }
  if(arr.length<size){
      newArr.push(arr);
  }

}

Demo:

function chunkArrayInGroups(arr, size) {
  // Break it up.
  var newArr =[];
  while(size<arr.length){
      newArr.push(arr.splice(0, size));
  }
  if(arr.length<size){
      newArr.push(arr);
  }
  return newArr;
}

console.log(chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7,8], 2));

Note:

There is no need for utilizing the result array since it merely duplicates the newArr. You could simply return newArr instead of creating a copy.

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

Is there a way to identify the index of user input when using the .map method?

I'm currently utilizing the Array.prototype.map() method to present an array within a table. Each row in this table includes both an input field and a submit button that corresponds to each element from the Array.prototype.map() function. Is there a w ...

Utilizing numerous X-axis data points in highcharts

I'm working with a line graph that dips straight down, like starting at (1, 100) and dropping to (1,0). The issue I'm facing is that Highcharts (https://www.highcharts.com/) only displays information for one of the points. Is there a way to make ...

Exploring the transparency of material lab autocomplete drop-down text for enabling multiple selections

Check out this demo for checkboxes and tags in Material UI The code below demonstrates an autocomplete component that functions correctly. However, the drop-down text appears transparent. Is there a way to fix this issue without modifying any libraries? ...

What is the most effective method to include JSON data containing various IDs at the end within an $http.get() request in AngularJS?

I'm facing a challenge with displaying JSON items that have an array of different ids at the end of the URL (/api/messages/:messageId). For instance, accessing /api/messages/12345 would return {"subject":"subject12345","body":"body12345","id":"12345"} ...

The default action is not triggered when the click event occurs

Hey there, I have been working on this <ol> list of events using jQuery (version 1.4.2). Everything is set up within the $(document).ready() function. Something strange is happening where when I click on the <li>, it triggers a click on the co ...

Tips on preventing form submission when clicking on another button within the same form

I created a shopping cart page with functionality to adjust the quantity using JavaScript. I have shared some of the HTML code below, <form action="payment.php" method="post"> <div class="qty__amount"> ...

The sort function in Reactjs does not trigger a re-render of the cards

After fetching data from a random profile API, I am trying to implement a feature where I can sort my profile cards by either age or last name with just a click of a button. Although I managed to get a sorted array displayed in the console log using the h ...

Converting JSON HTTP response to an Array in AngularJS 2: A Comprehensive Guide

As I work on a Http get request in Angular 2, the response returned is in JSON format. However, I am facing an issue when trying to use it in a ngFor loop because it is not formatted as an Array. Is there a way to convert JSON data to an Array in Angular ...

Integrate CSS and JavaScript files into Node Express

I am facing an issue including my CSS file and JavaScript file in a node-express application, as I keep getting a 404 not found error. Here is the code snippet that I am using: 1. In server.js var http = require('http'); var app = require(' ...

Managing global errors and intercepting requests in AngularJS can be easily achieved by utilizing $resource interceptors and global handlers for

My question pertains to the interceptor(responseError) of $resource. It is essential to note that I am working with angularjs version V1.3.6. The Issue: app.factory('authInterceptor',['$q', '$location', '$log', fun ...

Ionic ion-view missing title issue

I'm having trouble getting the Ionic title to display on my page: http://codepen.io/hawkphil/pen/oXqgrZ?editors=101 While my code isn't an exact match with the Ionic example, I don't want to complicate things by adding multiple layers of st ...

How can I verify if an unsupported parameter has been passed in a GET request using Express/Node.js?

Within my node.js backend, there is a method that I have: app.get('/reports', function(req, res){ var amount = req.param('amount'); var longitude = req.param('long'); var latitude = req.param('lat'); var di ...

Angular JS presents an exciting feature called Multiple Filters, which allows

I have a data representation application that displays information in table format with columns id, name, price, quantity The data is presented using ng-repeat. You can view it on this Plunker <body ng-controller="myController"> <h1>Data< ...

Setting a displacement/normal map for only one face of a cylinder

My current setup involves creating a cylinder using the following code: var geometry = new THREE.CylinderGeometry( 50, 50, 2, 128 ); The resulting shape is a flat cylinder resembling a coin. However, when I apply a displacementMap and normalMap, I notice ...

Using a physical Android device to test and run a Meteor mobile application

I'm struggling to get my Meteor app to run on my Android device (LG G2). Despite searching online for a solution, I haven't come across any similar issues. I followed the instructions carefully, added the Android platform to my project, and ran i ...

"Utilize parameter passing with mapGetters in the Vuex state management system

Hello there! I'm currently working on a Vue.js project and using modules. I am trying to get filtered data from a getter, but I'm unsure how to provide parameters. Specifically, I need to pass a 'name' parameter to the Getter. How can ...

Creating a dynamic progress bar that scrolls for multiple elements

I am currently working on implementing a scrolling progress bar to show users how much of an article within a div they have read. For reference, something similar can be seen on this site. I have created my custom progress bar and coded it on fiddle, whe ...

What is the best way to manage a significant volume of "business" data or objects within my JavaScript project?

I specialize in working with AngularJs and have a factory that provides services related to buildings. I am managing a large number of buildings (around 50-60) with multiple properties and sub-properties associated with each one (approximately 15-20, some ...

Access an external URL by logging in, then return back to the Angular application

I am facing a dilemma with an external URL that I need to access, created by another client. My task is to make a call to this external URL and then return to the home page seamlessly. Here's what I have tried: <button class="altro" titl ...

Add an extra filter solely to a single item within the ng-repeat directive

I've been working on a project in AngularJS that involves an object with key-value pairs displayed on the page. I need all keys to have a capitalized first letter, so I applied a filter. However, if the key is 'sku', then I require all lette ...