Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making one array exactly equal to another

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

like image 917
jskidd3 Avatar asked Jul 28 '13 10:07

jskidd3


People also ask

Can you make an array equal another array?

Set an Array Equal to Another Array in Java Using the copyOf() Method. The copyOf() method copies the content of an array and returns a new array.

Can I set two arrays equal to each other?

Two arrays are considered equal if both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are equal. In other words, two arrays are equal if they contain the same elements in the same order. Also, two array references are considered equal if both are null.

How do you make an array equal another in Javascript?

To append values of an array into another array, you can call the push() method of the Array object.

How do I make one array equal another in python?

ALGORITHM: STEP 1: Declare and initialize an array. STEP 2: Declare another array of the same size as of the first one. STEP 3: Loop through the first array from 0 to length of the array and copy an element from the first array to the second array that is arr1[i] = arr2[i].


1 Answers

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]
like image 187
Pawel Miech Avatar answered Nov 15 '22 18:11

Pawel Miech