Iterate through a specified number of elements in batches during each loop execution

Imagine we have an array like this:

let numbers = [1,2,3,4,5,6,7,8,9,10]

For example: If we want to create 5 sets with each pair of numbers in it, the result would look like this,

set1 = [1,2]
set2 = [2,4]
set3 = [5,6]

We can achieve this using the modulo operator(%), specifically because these are pairs - like so:

for (let i = 0; i < numbers.length; i++) {
  if(numbers[i] % 2 === 0)
    window['set' + i].push(numbers[i], numbers[i - 1])
}

There are various other methods, such as using nested loops.

I feel there might be a simpler solution out there, so I'd appreciate any suggestions!


Now, what's a more elegant way to iterate through every 'n' items in an array, apply a certain operation on them, and then proceed to the next 'n' elements?

Update:

The previous example focused on dealing with pairs from a 10-element array- That was just random. My aim isn't specifically about pairs - The main idea is how to loop through every N elements in an array, perform an operation, and then move on to the next N elements.

I'm not interested in generating new arrays - My query revolves around iterating over the original array exclusively.

Answer №1

To iterate through an array, you can simply use a basic for loop as shown below:

var chunkSize = 3;
for (var index = 0; index < myArray.length; index += chunkSize) {
    // Perform operations on myArray[index], myArray[index+1],...myArray[index+chunkSize-1]
}

Answer №2

To easily iterate through an array, simply add n to your index in a for loop:

for (var i = 0; i < arr.length; i += 2)
    console.log(arr[i], arr[i + 1]);

If you prefer automation, you can create a function that walks through the array by steps of n:

function stepThroughArray(arr, n, callback) {
    for (var i = 0; i < arr.length; i += n)
        callback(arr.slice(i, i + n));
}

stepThroughArray([1,2,3,4,5,6], 2, function (segment) {
    console.log(segment);
});

Answer №3

I have a feeling that there might be a simpler solution to this problem.

In my opinion, using more efficient would convey a better sentiment than simpler. When it comes to efficiency, the most optimal approach is to page through data only when necessary.

The code snippet below demonstrates this concept using the iter-ops library and the page operator:

import {pipe, page} from 'iter-ops';

const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

const i = pipe(arr, page(2)); //=> Iterable<number[]>

// Iterating through 'i' triggers paging,
// one page at a time:

for (const a of i) {
    console.log(a); //=> [1, 2], [2, 4], [5, 6]
}

By the way, I am the author of iter-ops.

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

Adjusting the value of 'let' based on the outcome

Can you assist me with this issue? I am attempting to assign a value to a let variable based on the following if conditional block. class Main extends React.Component{ render(){ let content = ''; firebase.auth().onAuthStateChanged(func ...

What is the process for replacing " with ' in my text?

Seeking assistance to run a SQL query from JavaScript that will execute in a SQL server. The query needs to locate a user in the database based on their username and password: var str = "SELECT * FROM Users where (username = " + params.user + ") and (pass ...

Setting the default value for drop-down menus in jqGrid form editing

I have a data object with 3 attributes: ID Abbreviation Description In my jqGrid setup, I've configured the grid to display the Abbreviation. During editing (using the Form Edit feature), I populate the dropdown list with ID/Description pairs usin ...

Designing a navigational sidebar featuring clickable links to specific locations on Google Maps

I'm currently utilizing a map script created by Derek Ender that integrates with Google Fusion Tables to display locations on a map. While the script is functioning well, I have received a request to make the sidebar list of locations clickable. The ...

Exploring Three.js raycasting in a non-full screen scenario

I've encountered some challenges with raycasting in three.js recently. The div element I'm using is not fullscreen, which I believe is causing issues with the raycast positioning that I'm struggling to resolve. let mouseVector = new THR ...

AngularJS directive element not displaying CSS styles properly

I've been grappling with this issue for the past few days and I just can't seem to crack it. Whenever I try adding a class to an AngularJS element directive, the styling appears in the code view of my browser (Chrome), but the styles themselves ...

What is the most secure method for conditionally wrapping input with state?

I used to check for errors and wrap the input and error message in a div conditionally. However, I faced an issue where the input would lose focus when re-rendered. Is there a way to wrap the input conditionally without losing focus on re-render if the err ...

Displaying specific elements within a two-dimensional array

Hi there, I'm fairly new to C programming and could use assistance with a school assignment that has been giving me some trouble. Assignment The task is to display the elements in an array marked in yellow within any given size matrix. Here is the c ...

Concealing Vimeo's controls and substituting them with a play/pause toggle button

I'm currently working on implementing the techniques demonstrated in this tutorial (), but unfortunately the code in the fiddle I put together doesn't appear to be functioning correctly. I'm at a loss as to what might be causing this issue. ...

Error in Internet Explorer when attempting to close a Fancybox iframe that plays a YouTube video

Even the FancyApps page itself contains the error mentioned below. If you visit using Internet Explorer 9, for example, follow these steps: Go to Internet Options > Advanced > Disable script debugging (Internet Explorer). Then click on the YouTube ( ...

What could be causing this code to keep looping?

This is my submission for a class project. The task given was: "Create a function that will kickstart the program and name it main(). From the main() function, invoke a function named getValue(). The getValue() function will prompt the user to input a num ...

JQuery functionality is disrupted by the update panel on the master page

I'm facing an issue with three anchors on the page - one for time in, one for time out, and one for the menu. Initially, everything works fine when the page loads for the first time. However, clicking on the time in or time out button causes the menu ...

Exploring the possibilities of web workers through object-oriented JavaScript, integrating ThreeJS and ScrollMagic

Currently, I am working on a personal website that incorporates Three.js and ScrollMagic using OO Javascript. The 3D objects on the site transform as the user scrolls, providing an interactive experience. While everything is functioning correctly, there is ...

What are some ways to design unique custom data grid toolbar elements?

I am having trouble syncing my custom toolbar buttons with the imported material data grid toolbar components. I would like them to match in style, specifically applying the material styles to my custom components. However, I have not been able to find a w ...

Ways to showcase an array within another array using VueJS

I encountered an issue with an API call that returns its result as an array within an array. Each nested array contains card transactions that need to be displayed. Upon examining the console output, I found: Array [ Object { "data": Array ...

Is there a way to dynamically modify a website's default viewport settings in a mobile browser?

When viewing a website in Landscape mode, everything looks good. However, switching to Portrait mode displays the message "Screen size not supported." I decided to test this on my desktop browser and discovered that adjusting the initial-scale:1 to initial ...

Using Three.js to apply a sprite as a texture to a spherical object

function generateLabel(icon, labelText, labelText2, labelText3, bgColor, fontColor, transparency, xCoordinate, yCoordinate, zCoordinate){ $('#imglabelcontainer').append('<div class="imglabel" id="imglabel'+labelText+'" style ...

The functionality of php.js is compromised

I've been attempting to integrate php.js into my scripts, but have encountered a problem. I debugged a function and loaded it onto a single page containing only jQuery and php.js, yet it is still not functioning properly. <script src="http://code. ...

Incorporate information into a JSON structure within SAPUI5

While diving into SAPUI5, I decided to challenge myself by creating a basic form. Unfortunately, my attempts are falling short as the new entry I'm trying to add to my JSON model isn't showing up in the file when I run my code. No error messages ...

Unspecified data transfer between child and parent components

I'm working on implementing a file selection feature in my child component, but I'm facing difficulties passing the selected file to the parent component. I'm struggling to find a solution for this issue and would appreciate some guidance. W ...