Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript, moving elements in an array from front to back

Tags:

javascript

I have an array that contains variables and functions. The array is 80 elements long. The first 20 elements are used together in a for loop. When the loop has completed, the first twenty elements are moved to the back of the array, and the for loop starts again.

I am rebuilding the array this way:

var a2=[the array with 80 elements];
run(a2);
function run(array){
  var n=array.slice(0,20); array.splice(0,20);
  var con=array.concat(n); a2=con;
  }

So I am basically indexing the (new) sliced array, re-indexing the (original) array after the splice, indexing a (new) array after the concat, and re-indexing the original again when I set it equal to the concat. This seems like it is too inefficient. Is there a more established approach to this?

like image 408
William Smith Avatar asked Sep 22 '26 15:09

William Smith


1 Answers

You don't need to slice() and then splice(). Splice() returns the removed elements, so you just need to do that:

var n = array.splice(0, 20);
a2 = array.concat(n);

To be completely clear, JavaScript's splice() method returns the removed elements, not the remaining elements.

Also, using globals is generally a bad idea, but you are also kinda mixing them in a weird way. If you are going to keep the variable global, I would either pass the original in as a parameter and return the result from the function:

var a2=[the array with 80 elements];
a2 = run(a2);

function run(array){
    var n = array.splice(0, 20);
    return array.concat(n);
}

OR

don't pass it in at all and just reference the global from the get-go:

var a2=[the array with 80 elements];
run();

function run(){
    var n = a2.splice(0, 20);
    a2 = a2.concat(n);
}
like image 192
Travesty3 Avatar answered Sep 25 '26 04:09

Travesty3