Using a for loop in Javascript with a specified increment value

I am working with an array containing 100 elements. My goal is to extract elements from the 10th to the 15th position (10, 11, 12, 13, 14, 15), then from the 20th to the 25th, followed by the 30th to the 35th, and so on in increments of 4, storing them in a new 2D array format. I have managed to store the values in a 2D array, but I am struggling with creating the desired gap.

One approach I explored involved chunking the array into sets of 6 elements (as I always need the first six elements of each "decade").

var newArr = [];
while(arr.length) newArr.push(arr.splice(0,6));

Alternatively, I found a function that splits an array into parts:

function splitArray(array, part) {
    var tmp = [];
    for(var i = 0; i < array.length; i += part) {
        tmp.push(array.slice(i, i + part));
    }
    return tmp;
}

console.log(splitArray(m1, 6));

However, before implementing this splitting logic, I need to figure out how to create a new array consisting of elements from positions 10-15, 20-25, and so forth. Can you provide guidance on how I can achieve this?

Answer №1

It is important to note that your function requires two separate parameters - one for the stride and another for the size of each part. The stride is used when incrementing the loop variable, while the size is used when creating the slice.

function divideArray(array, stride, size) {
    var temp = [];
    for(var i = 0; i < array.length; i += stride) {
        temp.push(array.slice(i, i + size));
    }
    return temp;
}

var arr1 = [];
for (var i = 0; i < 100; i++) {
    arr1.push(i);
}
console.log(divideArray(arr1, 10, 6));

Answer №2

A generator function eliminates the necessity to store interim outcomes. By adding an offset parameter, you can choose to skip the initial five values 0, 1, 2, 3, 4, 5:

function* splitArray(array, stride, size, offset = 0) {
  for (let i = offset; i < array.length; i += stride) {
    yield array.slice(i, i + size);
  }
}

// Example:
const array = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25];
console.log(...splitArray(array, 10, 6, 10));

Other than these specifics, this code is essentially the same as Barmar's response.

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

How can I customize the styling of Autocomplete chips in MUI ReactJS?

Trying to customize the color of the MUI Autocomplete component based on specific conditions, but struggling to find a solution. Any ideas? https://i.stack.imgur.com/50Ppk.png ...

Getting input elements with Puppeteer can be done by waiting for the page to fully load all elements within the frameset tag

Seeking to gather all input elements on this website: This is how the element source page appears. Below is my code snippet: const puppeteer = require("puppeteer"); function run() { return new Promise(async (resolve, reject) => { try { ...

Using Angular JS to submit forms on a regular basis

My HTML form is set up within an Angular controller with inputs, action, and other elements already defined. The only issue I'm facing is that the form does not have a traditional submit button. Instead, there is a separate button on the page outside ...

Dynamic Namespaces in Socket.io is a feature that allows for

I am currently working on implementing multiple namespaces in my app. As I receive route parameters, I dynamically create new namespaces. For example: var nsp = io.of('/'); var className; app.post('/class/:classID',function(req,res){ ...

Toggle accordion based on different situations dynamically

My goal is to dynamically select which accordion tab has the .active class based on the results of a switch/case statement. I have set up a switch/case statement to hide certain tabs based on the condition. <script> $(function () { $("#accordion-te ...

What could be causing my Express API registration route to fail when attempting to POST?

Currently, I'm in the process of developing a compact authentication system for a practice project that I've undertaken. As part of this endeavor, I am sending POST requests via Postman to my Express server located at http://localhost:4000/api/re ...

When utilizing Ionic with Angular, it is difficult to access the hardware back button on mobile devices that have buttons located within the display/screen

When trying to access the hardware back button in my app, I encountered an issue where I couldn't produce an alert message to the user before the app closed. After posting a question on Stack Overflow (link of the question) and receiving help from the ...

Connect main data to sub-component

Example Vue Structure: <Root> <App> <component> Main function in main.js: function() { axios.get('/app-api/call').then(function (resp, error) { _this.response = resp.data; }) ...

What is the best way to define a function in React hooks - using a function statement or

When working with a react hook and needing to define a function inside it, which approach is preferable? useEffect(() => { //... function handler() {} //... }, []); or should I use the newer const declaration instead? useEffect(() => { ...

Generating a list of prime numbers using a pre-defined function in Python

In my Python code, I have a function named prime_sieve(N) that assigns values of 0 or 1 to numbers based on whether they are prime or not. The issue lies in another function below this one, which is: import numpy as np def prime_sieve(N): nums = np.ara ...

How to use jQuery to maintain an image at the top of a div

Within my HTML, there is a primary root div element containing an image. <div id="root"> <img id="msg"/> </div> Using jQuery, I am able to prepend multiple div elements inside the main root div. However, the problem arises when these ...

Utilizing ASP.NET Core MVC, I have implemented a dynamic display of content through bootstrap cards featuring navigation tabs. These cards

Is it possible to display data from a database in ASP.NET Core MVC using a foreach loop to generate different bootstrap cards with navigation tabs? I have attempted this, and it seems to work partially. However, when I click on a navigation tab in the sec ...

What is the best way to show real-time values using chart js?

Just recently, I've delved into the world of web development and am eager to learn how to integrate chart js for real-time value display. Could anyone offer advice or guide me through the process? var data = []; var temp = []; async f ...

Showing submenu items in a jQuery menu system without causing the top level menu item to expand and fit

I currently have a menu system in place, which is quite simple, but there is an issue where the submenu items are larger than the top-level items. When hovering over the submenu items, the top-level menu expands to accommodate them. Is there a way to keep ...

Updating the Nuxt3 editing page with useFetch and $fetch for fetching data, along with a typed storage object that prevents loading issues

My journey with nuxt3 is still new. I am currently working on developing a new API-based app with nuxt3. Previous versions seemed to work "somehow," but they did not meet my expectations. Here are the things I am looking to cover, both in theory and in cod ...

Using nested ternary operations in React can cause issues with accessing local variables

Note: I encountered an issue where the extra curly braces around the first ternary result did not solve my initial problem. I replaced them with parentheses. Josep's suggestion to use getTime required me to equate the dates. The Date().setHours(0, 0, ...

Retrieve the runtime configuration object or file using Jest

Is there a way to access the Jest runtime config object or file path? I wanted to utilize runtime config properties in my custom matchers. // ./jest.config.js const path = require("path"); module.exports = { prop1: "foo", prop2: "bar" }; // my-custo ...

Exploring test suite pathways while utilizing ArcGIS JSAPI as an alternative loader within the Intern framework

I have been developing an application using the ArcGIS Javascript API and incorporating tests with Intern. While working on Windows 7 under IIS, I encountered some challenges but managed to overcome them by following the Intern tutorial and referring to so ...

Trigger an event in Angular using TypeScript when a key is pressed

Is it possible to activate a function when the user presses the / key in Angular directly from the keydown event? <div (keydown.\)="alerting()"> </div> <div (keydown.+)="alerting()"> </div> Both of these ...

Determine which JavaScript script to include based on whether the code is being executed within a Chrome extension

I am in the process of developing a Chrome extension as well as a web JavaScript application. I currently have an HTML container. I need the container.html file to include <script src="extension.js"> when it is running in the Chrome extension, and ...