What is the reason for the output being [['a', 'b']], as opposed to [['a','b'],['c','d']]?

I've been working on the freecodecamp Bonfire: Chunky Monkey problem and I'm almost there with the solution. However, I'm stuck on why the output is [['a', 'b']], instead of [['a', 'b'], ['c', 'd']]. Can anyone help me figure out what's wrong with my code?

function chunk(arr, size) {
  var array = [];
  var tmp = [];
  for(var i = 0; i < Math.floor(arr.length/size); i++) {
    for(var j = 0; j < size; j++) {
      tmp.push(arr[j]);
    }
    array.push(tmp);
    tmp = [];
    arr.splice(0,size);
  }
  return array;
}
chunk(['a', 'b', 'c', 'd'], 2);

Answer №1

By modifying the length of arr within the loop, you are causing the outer loop to only execute once. To avoid this issue, it's important to store the original length before making any changes:

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

    // Store the original length to prevent looping issues
    var iterations = Math.floor(arr.length / size);

    for (var i = 0; i < iterations; i++) {
        for (var j = 0; j < size; j++) {
            temp.push(arr[j]);
        }
        result.push(temp);
        temp = [];
        arr.splice(0, size);
    }
    return result;
}

Answer №2

Make sure to be cautious about altering the length of arr during each loop iteration to avoid issues with the loop running multiple times. Additionally, it is best to stick to a single loop for efficiency.

function chunk(arr, size) {
  var array = [];
  for(var i = 0; i < arr.length; i += size) {
    array.push(arr.slice(i, i + size));
  }
  return array;
}
chunk(['a', 'b', 'c', 'd'], 2);

Answer №3

Here is an alternate method:

function divide(arr, size) {
 var array = [];
 var temp = [];
 var index = 0;
 for(var i = 0; i < Math.ceil(arr.length/size); i++)
 {
   for(var j = index; j < index + size; j++)
   {
     arr[j] != undefined?temp.push(arr[j]):false;
   }
   index = index + size;
   array.push(temp);
   temp = [];
  }
 return array;
 }
 console.log(divide(['a', 'b', 'c', 'd', 'e', 'f'], 2));

Note: This method can handle arrays with both even and odd numbers of elements.

Answer №4

While many have provided answers with functional codes, my focus is on explaining the reasoning behind it.

At first glance, it may seem like the outer loop would iterate twice, given that Math.floor(arr.length/size) returns a value of 2 initially:

for(var i = 0; i < Math.floor(arr.length/size); i++) {
    // ....
}

However, it's important to note that in the first iteration, the array arr is actually chunked:

arr.splice(0,size); // arr is ['c', 'd'] after this step

When the loop moves to the second iteration, i is now 1 and Math.floor(arr.length/size) evaluates to Math.floor(['c', 'd']/2). This condition results in a failure, causing the loop to exit prematurely. Therefore, contrary to initial expectations, there isn't a second iteration.

Answer №5

Example of utilizing a loop to configure chunk size.

function createChunks(inputArray, chunkSize) {
  var outputArray = [];

  for (var i = 0, len; i < chunkSize; i++) {
    len = inputArray.length;
    if (len >= chunkSize) {
      outputArray[i] = inputArray.splice(0, chunkSize === 1 ? len : chunkSize);
    } else if (len > 0) {
      outputArray[i] = inputArray.splice(0, len);
    }
  }
  return outputArray;
}

var output = createChunks(['x', 'y', 'z', 'w'], 1);
console.log(output);

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

Communication between child and parent components in Vue.js is an essential feature

Attempting to invoke functions from my component to Vue for the login process. This is the code snippet of my component : Vue.component('auths', { data: function() { return { ip: '', sessiontoken: '' } ...

Switch up a font style using JavaScript to apply a Google font effect

I am attempting to implement a discreet hidden button on a website that triggers a unique Google font effect for all of the h1 elements displayed on the page. However, I am uncertain about the process and unsure if it is achievable. Below is the code snipp ...

Avoid the need to refresh the HTML content every time there is a change in the Angular $

One of the challenges I'm facing is with a for loop in my JavaScript: for (var i=0;i<2;i++) { $scope.widget = widgets[i]; $scope.header = widgets[i].data.header; $scope.items = widgets[i].data.items; $scope.footer = widgets[i].data ...

What is the best method for displaying plain text using the br tag?

My component looks like this: class News extends Component { state = { isSimple: this.props.isSimple } render() { return ( <div> <div className="extended">extended</div> simple text </div&g ...

Channeling requests from webpack dev server to .net MVC website

I am working on incorporating Vue into my .net MVC project. After installing Vue using the CLI, I included the following vue.config.js: module.exports = { devServer: { proxy: { '/': { target: 'http://mvcsite.local', ...

Angularjs directive retrieves infowindow DOM element from Google Maps

In order to apply some style fixes to the Infowindow, I am trying to select the element with the class 'gm-style-iw'. This selection process is taking place within an angularjs directive. <div ui-view="full-map" id="full-map" class="mainMap c ...

Can you explain the purpose of FunctionConstructor in typeScript?

As I delved into the Typescript Ecmascript source code, I stumbled upon this intriguing snippet: interface FunctionConstructor { /** * Creates a new function. * @param args A list of arguments the function accepts. */ new(...args: st ...

Updating/Timer feature for a single feed out of two -- Combining data with $q.all()

I'm revisiting a question I previously asked here. The approach I took involved using the $q.all() method to resolve multiple http calls and then filtering and merging the data. Everything was working fine, but now I want to refresh one of the feeds ...

How can I display SQL results in a Jade page using Node, Express, and MySQL?

My application built with Node.js and Express is connected to a MySQL database for monitoring purposes. The code structure is as follows: In the Node file: app.get('/banners', function(req,res){ connection.query("SELECT * FROM banner_store_ ...

Error: React Native Component Exception - a potential hiccup in

As a newcomer to React Native, I've encountered an issue while trying to bind data from a local JSON server API. Everything worked fine when I used a class component for my EventList, but after integrating Navigation in App.js and changing it to a fun ...

billboard.js: The 'axis.x.type' property is conflicting with different data types in this context

axis: { x: { type: "category" } }, An issue has arisen: The different types of 'axis.x.type' are not compatible with each other. The value of 'string' cannot be assigned to '"category" | &qu ...

Unpacking a props object results in an undefined value

I've been struggling to set up a data-grid in react because I'm facing issues with accessing the data from my props. Whenever I try to access or destructure the prop, it shows up as "undefined" in my console. This problem only arises when the p ...

Resolving Node.js Absolute Module Paths with TypeScript

Currently, I am facing an issue where the modules need to be resolved based on the baseUrl so that the output code is compatible with node.js. Here is my file path: src/server/index.ts import express = require('express'); import {port, database ...

Issue with JQuery: Inability to deactivate an element after receiving an Ajax response

My dynamic dialogue box, generated via Ajax return, presents a challenge involving the dynamically changing drop-down list element $('#functionSelect'). I require this list to trigger disabling of input fields within the dialogue box upon changes ...

Utilizing several carets in a single or multiple text areas and input boxes

Just a quick question... Can a textbox have two carets simultaneously, or can we have two separate textboxes both focused at the same time? I am aware of simulating this using keydown listeners but I'm specifically looking for visible carets in both ...

A step-by-step guide on storing JSON data into a variable using NodeJS

Just starting out with Node.js and running into an issue. I need to figure out how to extract and save data from a JSON object retrieved from the GitHub API. var http = require("http"); var express = require('express'); var app = express(); var ...

Clicking twice in a row on a map

I am encountering an issue while collecting user input from an infowindow. When I click the 'Save' button in the infowindow to save the input, it inadvertently results in moving my marker on the map by clicking somewhere else. All I really want t ...

Transfer the updated variable from a static JavaScript file to Next.js

I am facing a challenge with a conditional render in my component. I am unable to display the value of a variable. In one file, I have all my functions that I export in index.js import FunctionServices from "../services/functionServices" export ...

The module 'AppModule' is importing an unexpected value 'AppAsideModule'. To resolve this issue, make sure to include an @NgModule annotation

Recently, I attempted to upgrade my Angular project from version 13 to version 17. However, during the process, I encountered an error stating "Unexpected value 'AppAsideModule' imported by the module 'AppModule'. Please add an @NgModul ...

Encountered an invalid prop type error while employing CSSTransition

Encountering an issue with the implementation of CSSTranstion for React. The purpose is to animate the mobile menu in a small application. Everything was functioning properly until the inclusion of the react-transition-group package, specifically using < ...