Struggling to pinpoint the problem with splitting an array into chunks

Could someone help me understand why my function isn't properly splitting the array into chunks as intended? I've written a function that is supposed to divide an array into subarrays based on the second argument provided. For example, if we have [1, 2, 3, 4] and the number 2 as the second argument, the output should be [[1, 2], [3, 4]]. However, when I run my code, it only returns the first chunk correctly while subsequent chunks are empty arrays. I'm increasing the index by the value of the second argument in each iteration, so I can't pinpoint why it's not working as expected. Any insights or assistance in identifying where the logic error lies would be greatly appreciated.

let arr = [1, 2, 3, 4, 5, 6]

function test(arr, num) {
    let idx = 0;
    let newArr = []
    while (idx < arr.length) {
      newArr.push(arr.slice(idx, num))
      idx = idx + num
    }
    return newArr
}

console.log(test(arr, 2))

Answer №1

When using Array#slice, always remember to pass the index as the second parameter, not the length of the slice.

For instance, if you want to slice from index 2 with a length of 4, the correct parameters should be 2 and 6 respectively.

                    chunks
values   1 2 3 4 5 6              
indices  0 1 2 3 4 5              
slice    0 2           1 2         
             2 4       3 4         
                 4 6   5 6         

function customSlice(arr, length) {
    let idx = 0;
    let newArr = [];
    while (idx < arr.length) {
        newArr.push(arr.slice(idx, idx += num));
    }
    return newArr;
}

let arr = [1, 2, 3, 4, 5, 6];

console.log(customSlice(arr, 2));

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

Guide to turning off alerts for identifiers starting with an underscore (_)

Exploring ReactJS Development with ESLint Being a developer working with ReactJS, I find great value in the automated assistance provided by ESLint for detecting code issues like unused identifiers. If you're interested in experimenting with ESLint, ...

In Swift, search through an array to check if the values of a specific parameter exceed 2000

Is there a way to search within an array for a specific parameter, such as location, and determine if any of the locations have a value of 2000 or higher? I would also like to print the number of locations (rows) that meet this criteria. Thank you! ...

Enable form submission using the ENTER key when the focus is outside of an input field

Within my form, I have a div element that is focusable using tabindex="0". While this setup works well overall, I am facing an issue with submitting the form using the enter key. The submission works when an input field is in focus but not when the div has ...

The modelErrors property in the json response has not been defined

Currently, I am attempting to parse a JSON response. The JSON response is being received in the responseText property. Initially, I receive the response from JSON structured as shown below: {"Success":false,"Error":true,"ErrorType":1,"ModelErrors":{"Name" ...

disable comment section in angular and update display

Is there a way to revert back to the original view after clicking on the edit button when the view is changed using ng-if? I want to go back by clicking the cancel button. <div class="timeline-body"> <div marked="cmnt.conten ...

What is the method for obtaining the values from these newly generated text fields?

Every time I click on the "ADD TEXTBOX" button, a new HTML textbox is dynamically created using jQuery's append method. However, I am struggling to figure out how to retrieve and store the values of these textboxes in PHP. $(w).append('<div&g ...

Retrieving data within individual HTML elements

Is there a way to combine and extract data from different HTML tags for validation purposes? I am interested in fetching values from two separate input fields, merging them into one string, and passing this combined string as an argument to a function with ...

Unit test produced an unforeseen outcome when executing the function with the setTimeout() method

When manually testing this code in the browser's console, it performs as expected. The correct number of points is displayed with a one-second delay in the console. const defer = (func, ms) => { return function() { setTimeout(() => func.ca ...

How to select specific folders for packaging with asar within an Electron app

I'm currently working on an Electron application and experimenting with using asar to package the node_modules and sources directories, while excluding other directories. However, I've run into an issue where when building the application with a ...

Converting JSON data into an array using JavaScript

Stored in a variable named "response", I have the JSON value below: {"rsuccess":true,"errorMessage":" ","ec":null,"responseList":[{"id":2,"description":"user1"},{"id":1,"description”:"user2"}]} var users=response.responseList; var l = users.length; H ...

In JavaScript, Identify the filename selected to be attached to the form and provide an alert message if the user chooses the incorrect file

I have a form in HTML that includes an input field for file upload. I am looking to ensure that the selected file matches the desired file name (mcust.csv). If a different file is chosen, I want to trigger a JS error. Below is the form: <form name="up ...

Achieving JSON element sorting in the most effective way

https://i.stack.imgur.com/NQbdN.png Each array contains the following information: {{ id: 39, treaty_number: "qwe", insurant_name: "222", belonging_to_the_holding_company: "test", date_start: "2016-04-15", etc }} Is there a way to sort each array in asc ...

Increase the Step Size of an HTML Number Input by Holding Down the Time

Is there a way to implement increasing increment/step size for number inputs in HTML based on how long the user holds the stepper arrows? For instance, starting at step size=1 and gradually ramping up to larger increments like 5, 10, 20, etc. after holdin ...

Validating Input Field with Regular Expression in JavaScript/TypeScript to Avoid Starting with Zero

I need to create a RegEx for a text field in Angular / TypeScript that limits the user to inputting only a 1-3 digit number that does not start with 0. While it's straightforward to restrict input to just digits, I'm struggling to prevent an inpu ...

What is the best way to arrange an array of objects based on a specific attribute?

Ordering object based on value: test": [{ "order_number": 3, }, { "order_number": 1, }] Is there a way to arrange this so that the object with order_number 1 appears first in the array? ...

Merge 2 datasets together in Laravel by using the "put" method to combine them under the same key, ensuring that the

I am dealing with two relatively straightforward collections at the moment. The first collection contains 2 values within the 'products' array, while the second is a simple array: $collection_1 = collect([ 'products' => [ ...

Displaying image alt text on hover using pure JavaScript

Is there a way to hover over images on my webpage and display their alt text using vanilla javascript, without relying on jQuery? Here is the code for my images: <a href="<?php echo $displayData['href']; ?>" class="group"> <d ...

I'm struggling to get my React project up and running due to an unexpected error that I encountered

click here for image description Greetings Earthlings! I seem to be experiencing difficulties with executing the command "npm run start" and could use some assistance. Much appreciation in advance! I initially suspected it might be related to the Node.js ...

Listening for events with $rootScope.$on inside a service or factory

I'm encountering a peculiar issue with the $rootScope.$on method within a service or Factory. Here's an example of the service: app.service('testService', function($rootScope){ this.var1 = 5; this.change = function(n){ this.var1 ...

Reverse action on Angular checklist-model checkboxes

I have successfully implemented checklist-model.js for angular to select from a dynamically generated list of objects. However, I now need to create the functionality to move unchecked checkboxes into a new array (and remove them when checked again). Can a ...