Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy or duplicate an array of arrays

Tags:

javascript

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,

like image 544
Jeremy Avatar asked Feb 22 '12 16:02

Jeremy


People also ask

How do you duplicate an array?

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.

Can arrays be copied?

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.

Can an array be copied to another array?

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.


2 Answers

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;
}
like image 70
Churk Avatar answered Oct 19 '22 16:10

Churk


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

like image 26
georg Avatar answered Oct 19 '22 14:10

georg