0

Is there any faster/better way to "reset" the array than what Im currently doing?

-- populate arrayA and arrayCache using for loop

-- shuffle arrayA

/* empty arrayA */
arrayA = [];  -

/* THIS IS THE IMPORTANT PART, reset the array (load values from arrayCache into arrayA) */
for(i = 0; i < arrayCache.length; i++)
{
  arrayA.push(arrayCache[i]);
}

I populate (using loop) 2 arrays (arrayA and arrayCache), then iterate and shuffle (if condition is met) the first arrayA and then I need to reset it to its original state.

Note - if I simply do arrayA = arrayCache, then arrayCache is changed simultaneously with arrayA

  • Possible [duplicate of this posting](http://stackoverflow.com/questions/3978492/javascript-fastest-way-to-duplicate-an-array-slice-vs-for-loop) – Alp Jun 23 '15 at 07:16

2 Answers2

0

I think you can do, but it will change the array referenced by arrayA

-- populate arrayA and arrayCache using for loop

-- shuffle arrayA

/* empty arrayA */
arrayA = [];  -

/* THIS IS THE IMPORTANT PART, reset the array (load values from arrayCache into arrayA) */
arrayA = arrayCache.slice(0)

If you want to modify the original array referred by arrayA then

arrayA.push.apply(arrayA, arrayCache)
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
0

Also this would work

arrayA=arrayCache.concat();
nik
  • 2,455
  • 21
  • 26