James
James

Reputation: 1456

Javascript Array Loop through specific indexes in array

I'm working in JavaScript native project where I have a huge array with 50k elements (json objects).
When i loop through this array it take a huge time > 2h

for(var i = 1; i <= myArray.length; i++) {
// my code here for each element
}

So what I plan to do is loop through specific indexes in array:

// loop one from index 0 to 10k

// loop one from index 10k to 20k

...

Each loop I will make it in a separate process

Upvotes: 0

Views: 132

Answers (1)

Brandon McConnell
Brandon McConnell

Reputation: 6119

If you're just wanting to loop through specific indexes, would this work?

Using Math.min ensures that even when progressing in 10k increments, you never exceed the length of the array. With an array of 24736 items, the first loop would run from 0 to 9999, the second loop would run from 10000 to 19999, and the third loop would run from 20000 to 24736.

for(let i = 0; i < Math.min(myArray.length, 10000); i++) {
    // ...
}
for(let i = 10000; i < Math.min(myArray.length, 20000); i++) {
    // ...
}
for(let i = 20000; i < Math.min(myArray.length, 30000); i++) {
    // ...
}

You can even nest these loops to perform actions between each loop, like this:

const myArray = Array(54723).fill();

for (let n = 0; n < myArray.length; n += 10000) {
  for(let i = 0; i < Math.min(myArray.length, 10000); i++) {
      // ...
  }
  console.log(Math.min(myArray.length, n + 10000));
}

Upvotes: 1

Related Questions