# Tweening an Array

This thread was started before GSAP 3 was released. Some information, especially the syntax, may be out of date for GSAP 3. Please see the GSAP 3 migration guide and release notes for more information about how to update the code to GSAP 3's syntax.

## Recommended Posts

I have two arrays in javascript, here's a small example:

```arr1 = [0, 0, 0, 0];
arr2 = [3,6,3,5];```

I want to tween all the numbers from arr1 to arr2. So,

```from 0 to 3
from 0 to 6
from 0 to 3
from 0 to 5```

I tried doing something like:

`TweenLite.to(this, duration, {arr1:arr2});`

but it didn't work, so I tried again:

```for (var i = 0; i < arr1.length; i++) {
TweenLite.to(this, duration, {arr1[i]:arr2[i]});
}```

But that threw up an error.

What's the best way to do this? In my real code, I actually have upwards of 14 elements in the array.

##### Share on other sites

Luckily in javascript, Arrays are actually Objects, and Array elements are just named Object properties (the only caveat is that named properties that start with a number can only be accessed myArray[0] ... myArray.0 won't work).

You can think of arr1 and arr2 as being the same as this:

```var arr1 = { 0:0, 1:0, 2:0, 3:0 };
var arr2 = { 0:3, 1:6, 2:3, 3:5 };
```

You can simply tween arr1 to the values in arr2 with this:

`TweenLite.to(arr1, duration, arr2);`

arr1 is the target object, and arr2 is your list of named properties and their values. With that data set you would be tweening the following (just what you are asking for):

arr1[0] 0  ->  arr2[0] 3

arr1[1] 0  ->  arr2[1] 6

arr1[2] 0  ->  arr2[2] 3

arr1[3] 0  ->  arr2[3] 5

It makes it a bit awkward to attach extra options to the tween vars though, but since arr2 is an Object anyway, you can just attach more properties to it (unless you need arr2 to be untouched? in that case just copy it first and attach to and tween using the copy). Check it out here:

See the Pen xcwEK by jamiejefferson (@jamiejefferson) on CodePen

• 5
##### Share on other sites

Wow, absolutely excellent and comprehensive response. Thanks a lot!

##### Share on other sites

I'll just add that this was close:

```for (var i = 0; i < arr1.length; i++) {
TweenLite.to(this, duration, {arr1[i]:arr2[i]});
}```

but what it really needs to be is this:

```for (var i = 0; i < arr1.length; i++) {
TweenLite.to(arr1, duration, {i:arr2[i]});
}```

except... now the named property is actually i, not the number stored in i. I thought maybe {String(i):arr2} might work, but it seems like you can't generate the Object's property names when initialising an Object. It needs to be done this way it seems:

```for (var i = 0; i < arr1.length; i++) {
var props = {};
props[i] = arr2[i];
TweenLite.to(arr1, duration, props);
}```
• 2