Properly Cloning Arrays in JavaScript

This one came up during a discussion about Prototype 1.5.1 while looking through its documentation. Basically when you do the following in JavaScript, you are not copying the array, but rather creating another reference to it. In order to properly clone or duplicate an array you have two choices; loop through the array and copying its values or using the concat method. I personally suggest the concat method since its cleaner and keeps the operations withing the native code of your browser.

	function cloneArray( originalArray )
	{
		return originalArray.concat();
	}

As always there is a pre-extended version of this functionality in the Array class when using Prototype.

	var originalArray = [document.getElementById( "someId1"), new Object(), new Array()];
	var cloneArray = originalArray.clone();

The following will not work the way it is intended in most cases as the array second assignment will just be a secondary reference to the original array. Meaning if you alter array2 using any methods or direct action you will also alter array1.

var array1 = [document.getElementById( "someId1"), new Object(), new Array()];
var array2 = array1;
array1.shift(); //will alter array1 and array2;
  • Reddit
  • del.icio.us
  • Google Bookmarks
  • StumbleUpon
  • Technorati
  • Digg

Leave a Reply