How can I loop trough a very large array, and still be able to move elements to the end of the array without breaking the loop?
In the loop I am consuming the elements, but some of them depend on others, and those I want to move at the end. Eventually all elements will be consumed, so the loop will not be infinite.
I know the easy way is to just use a secondary array and not alter original array in the loop, but data is very large and it would be very slow
How can I loop trough a very large array, and still be able to move elements to the end of the array without breaking the loop?
In the loop I am consuming the elements, but some of them depend on others, and those I want to move at the end. Eventually all elements will be consumed, so the loop will not be infinite.
I know the easy way is to just use a secondary array and not alter original array in the loop, but data is very large and it would be very slow
Share Improve this question asked 2 days ago AlexAlex 68k185 gold badges459 silver badges650 bronze badges2 Answers
Reset to default 3You can use the "Two-Pointer" Method for this in JavaScript. The key idea to iterate over the array and do the following:
Moving specific elements to the last
Without breaking the loop or creating a new array
A code for this purpose can be as follows:
function processLargeArray(arr) {
let end = arr.length - 1;
for (let i = 0; i <= end; ) {
if (shouldMoveToEnd(arr[i])) {
[arr[i], arr[end]] = [arr[end], arr[i]];
end--;
} else {
processElement(arr[i]);
i++;
}
}
}
function shouldMoveToEnd(num) {
return num % 2 === 0;
}
function processElement(num) {
console.log("Processing:", num);
}
// Example
let arr = [3, 2, 1, 4, 5, 6, 7, 8];
processLargeArray(arr);
console.log("Final array:", arr);
Output:
Processing: 3
Processing: 7
Processing: 1
Processing: 5
Final array: [
3, 7, 1, 5,
6, 4, 8, 2
]
=== Code Execution Successful ===
Advantages:
- In-place modification
- Efficient Swapping
- Prevents Infinite Loop
Time Complexity : O(N) where N is the number elements in the array
Space Complexity : O(1) because no additional space is used
You can modify the array in-place using a single loop and an index pointer (i):
If an element needs to be moved, remove it using splice() and push it to the end with push().
Do not increment i in this case, since the next element shifts into the same index.
If the element is processed normally, increment i.