I'm trying to make a function that duplicates an array of arrays. I tried blah.slice(0); but it only copies the references. I need to make a duplicate that leaves the original intact.
I found this prototype method at http://my.opera.com/GreyWyvern/blog/show.dml/1725165
Object.prototype.clone = function() {
var newObj = (this instanceof Array) ? [] : {};
for (i in this) {
if (i == 'clone') continue;
if (this[i] && typeof this[i] == "object") {
newObj[i] = this[i].clone();
} else newObj[i] = this[i]
} return newObj;
};
It works, but messes up a jQuery plugin I'm using - so I need to turn it onto a function... and recursion isn't my strongest.
Your help would be appreciated!
Cheers,
To duplicate an array, just return the element in your map call. numbers = [1, 2, 3]; numbersCopy = numbers. map((x) => x); If you'd like to be a bit more mathematical, (x) => x is called identity.
Answer: There are different methods to copy an array. You can use a for loop and copy elements of one to another one by one. Use the clone method to clone an array. Use arraycopy() method of System class.
arrayCopy(). This copies an array from a source array to a destination array, starting the copy action from the source position to the target position until the specified length. The number of elements copied to the target array equals the specified length.
function clone (existingArray) {
var newObj = (existingArray instanceof Array) ? [] : {};
for (i in existingArray) {
if (i == 'clone') continue;
if (existingArray[i] && typeof existingArray[i] == "object") {
newObj[i] = clone(existingArray[i]);
} else {
newObj[i] = existingArray[i]
}
}
return newObj;
}
For example:
clone = function(obj) {
if (!obj || typeof obj != "object")
return obj;
var isAry = Object.prototype.toString.call(obj).toLowerCase() == '[object array]';
var o = isAry ? [] : {};
for (var p in obj)
o[p] = clone(obj[p]);
return o;
}
improved as per comments
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With