Making one array exactly equal to another

18,873

Solution 1

If you just need a copy of the elements of an array you can simply use slice like this:

a = [1,2,3]
copyArray = a.slice(0)
[1 , 2 , 3]

As for why you should not use assignement here look at this example:

a = [1,2,3]
b = a 
a.push(99)
a 
[1,2,3,99]
b
[1,2,3,99]

If you copy an array you don't have this problem:

 a = [1,2,3]
 b = a.slice(0)
 a.push(888)
 a 
 [1,2,3,888]
 b 
 [1,2,3]

Solution 2

For a deep copy of your array, do this (REFERENCE):

function deepCopy(obj) {
    if (Object.prototype.toString.call(obj) === '[object Array]') {
        var out = [], i = 0, len = obj.length;
        for ( ; i < len; i++ ) {
            out[i] = arguments.callee(obj[i]);
        }
        return out;
    }
    if (typeof obj === 'object') {
        var out = {}, i;
        for ( i in obj ) {
            out[i] = arguments.callee(obj[i]);
        }
        return out;
    }
    return obj;
}
Share:
18,873

Related videos on Youtube

jskidd3
Author by

jskidd3

Web developer from Southampton, United Kingdom.

Updated on June 04, 2022

Comments

  • jskidd3
    jskidd3 almost 2 years

    I have two arrays:

    var array1 = [1, 2, 3];
    var array2 = [4, 5, 6];
    

    I want array 1 to be exactly equal to array 2. I've been told I can't simply do:

    array1 = array2;
    

    If I can't do this, how can I make array1 equal to array2?

    Thanks

    • DCoder
      DCoder over 10 years
      array1 = array2.slice(0)?
  • jskidd3
    jskidd3 over 10 years
    Does this have the exact same effect as doing 'copyArray = a'?
  • jskidd3
    jskidd3 over 10 years
    Is this the same as doing clone = originalArray?

Related