最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Move elements inside array while looping it - Stack Overflow

programmeradmin1浏览0评论

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 badges
Add a comment  | 

2 Answers 2

Reset to default 3

You can use the "Two-Pointer" Method for this in JavaScript. The key idea to iterate over the array and do the following:

  1. Moving specific elements to the last

  2. 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:

  1. In-place modification
  2. Efficient Swapping
  3. 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):

  1. If an element needs to be moved, remove it using splice() and push it to the end with push().

  2. Do not increment i in this case, since the next element shifts into the same index.

  3. If the element is processed normally, increment i.

发布评论

评论列表(0)

  1. 暂无评论