-1

I'm working with a buffer array that I am periodically checking. When I am mapping through the elements, I would like access the element using the shift method, this way I would get the next element in the array and would also remove it. Is there a way to do this in a map? Thank you!

I currently have a naive solution, which is prone to race conditions.

if (timestep) {
    bufferArray.map((mvt) =>{
        console.log(mvt)
    });
    bufferArray = [];
} 
Jani
  • 507
  • 3
  • 21

1 Answers1

1

As I would like to go through the elements of the array one by one and remove the current element from the array. For this reason a simple and great solution is to use a while loop with the shift method. For example:

let arr = [0,1,2,3,4,5];

while (arr.length)
{
    let current = arr.shift()
    // do something with current
}
Jani
  • 507
  • 3
  • 21