For example, when pulling items from the middle of the array : [0,1,2,3,4,5,6,7] (length is 8)
const arr=[0,1,2,3,4,5,6,7];
while(arr.length>0){
document.write(arr.splice(arr.length/2,1)+" ");
}
the order of index of items that would pull is : 4 3 5 2 6 1 7 0
But now I want to iterate the index but not modifying the original array and without generating the sequence array (mainly due to the original array is a bit large in real code,also want an simpler algorithm), how can I iterate it with for loop only? I tried: (c=8)
for(let i=0,c=8,half=Math.floor(c/2);i<c;i++){
document.write(half+Math.floor(i/2)+(i%2==0?1:-1)+" ");
}
which the output is 5 3 6 4 7 5 8 6 instead of 4 3 5 2 6 1 7 0, which is not working.
6
Answers
You can see how it works right. You are basically finding the middle element and then going towards the beginning of the array or the end. Earlier you could do it, because the array length was shortening but now you do not have that luxury. So you have to simulate that.
You can have a
direction
flag, which tells the pointer where to go.You can have a
step
variable, which tells how many steps to take from the center.Since we have to handle for both odd and even length lists, there is another variable which indicates the originalDirection we had started going out with.
The above does exactly what you want without altering the array.
With
i
starting at 0, the corresponding sequence ofMath.floor(i/2)
values starts with 0, 0. You want only one 0 at the start, which you can achieve by usingMath.ceil
instead, for example:That said, do you also care about odd numbers of elements? Because that requires reversing direction:
So, in general,
Find middle point by calling
Math.ceil(arr.length / 2);
.Start a loop from 0 and up to this point and either add or subtract as you go along.
On the first run where your loop value is 0, skip the second value output
You can achieve this by directly calculating the indices you want to access using a loop:
That is an ideal job for a generator function. Side note: don’t use
document.write
.Strange, but nobody offered to use just 2 indices:
And don’t use generators with big arrays, they are notoriously slower than usual loops.
And a benchmark: