JavaScript: Is there a better way to retain your array but efficiently concat or replace items?
        Posted  
        
            by 
                Michael Mikowski
            
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by Michael Mikowski
        
        
        
        Published on 2013-10-30T02:38:03Z
        Indexed on 
            2013/10/30
            3:54 UTC
        
        
        Read the original article
        Hit count: 206
        
JavaScript
|Performance
I am looking for the best way to replace or add to elements of an array without deleting the original reference. Here is the set up:
var a = [], b = [], c, i, obj;
for ( i = 0; i < 100000; i++ ) { a[ i ] = i; b[ i ] = 10000 - i; }
obj.data_list = a;
Now we want to concatenate b INTO a without changing the reference to a, since it is used in obj.data_list. Here is one method:
for ( i = 0; i < b.length; i++ ) { a.push( b[ i ] ); }
This seems to be a somewhat terser and 8x (on V8) faster method:
a.splice.apply( a, [ a.length, 0 ].concat( b ) );
I have found this useful when iterating over an "in-place" array and don't want to touch the elements as I go (a good practice). I start a new array (let's call it keep_list) with the initial arguments and then add the elements I wish to retain. Finally I use this apply method to quickly replace the truncated array:
var keep_list = [ 0, 0 ];
for ( i = 0; i < a.length; i++ ){ 
  if ( some_condition ){ keep_list.push( a[ i ] );
}
// truncate array
a.length = 0;
// And replace contents
a.splice.apply( a, keep_list );
There are a few problems with this solution:
- there is a max call stack size limit of around 50k on V8
- I have not tested on other JS engines yet.
- This solution is a bit cryptic
Has anyone found a better way?
© Stack Overflow or respective owner