Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop 'n' elements in groups in each iteration

Let's say I have this array:

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

Example: I want to construct 5 arrays with each pair in it so it becomes,

arr1 = [1,2]
arr2 = [2,4]
arr3 = [5,6]

This can of course be solved with the modulo operator(%), since those are simply pairs - so it becomes:

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

There are other ways, e.g with nested loops etc.

I'm feeling that this can be solved with a simpler way however, so I'd like to see more suggestions


So what's an elegant way to loop every 'n' items in an array, perform some operation on them and then move on to the next 'n' elements.

Update:

The example above deals with 2 elements in a a 10-element array- That's purely random. I'm not looking for a way to deal with pairs in an array - The question is about how to loop every N elements in an array, perform whatever operation on those N elements and move on to the next N elements

I'm also not looking to create new arrays - The question has to do with iterating over the original array, only.

like image 527
nicholaswmin Avatar asked May 13 '26 21:05

nicholaswmin


2 Answers

Use plain old for loop, like this

var N = 3;
for (var i = 0; i < array.length; i += N) {
    // Do your work with array[i], array[i+1]...array[i+N-1]
}
like image 185
thefourtheye Avatar answered May 16 '26 11:05

thefourtheye


Just increment by n in your for loop:

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

You can write a function to automate walking through an array by n for you:

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

walk([1,2,3,4,5,6], 2, function (segment) {
    console.log(segment);
});
like image 29
Casey Chu Avatar answered May 16 '26 09:05

Casey Chu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!