A Flash Developer Resource Site

# Thread: Array Order Swapping Question

1. ## Array Order Swapping Question

Ok, say I have an m-d array with 5 values in each of 10 array rows

data[0][0] thru data[9][4]

What would be the best way to swap the data in say row 3 (data[2][*]) with the data in row 6 (data[5][*])?

In other words, just changing the order of the rows.

Im very "old skewl", and my old skewl thinking suggests I should just create a temp "buffer" s-d array and copy the contents of the first row to the buffer, then copy the contents of the second row to the first, then copy the buffer contents to the second row. But, there's GOT to be a more efficient way!

Any help would be appreciated!

Ahhhk!

2. I don't know, I think a temp variable seems a reasonable way to do this,

Code:
```var data = [];
data.push(["0,0", "0,1"]);
data.push(["1,0", "1,1"]);
data.push(["2,0", "2,1"]);
data.push(["3,0", "3,1"]);

showValues();
var tmp = data[2].slice();
data[2] = data[0].slice();
data[0] = tmp;
delete tmp;
showValues();

function showValues() {
for (var i = 0; i < data.length; ++i) {
for (var j = 0; j < data[i].length; ++j) {
trace("data[" + i + "][" + j + "] = " + data[i][j]);
}
}
trace("------------");
}```

3. Here's another approach... where "m" is your array, and "r1" and "r2" are the rows to swap.

Code:
```function swapRows(arr, r1, r2) {
var a = arr.slice(r1, r1+1);
var b = arr.slice(r2, r2+1);
var c = arr.splice(r2, 1, a);
var d = arr.splice(r1, 1, b);
return arr;
}
var r1 = 2;
var r2 = 4;
var newm = swapRows(m, r1, r2);
trace(newm);```
Edit: Oh, but nix mine. catbert303, your solution is cleaner. Thanks for sharing!

4. Thanks catbert and winterac!

The "data[2] = data[0].slice();" helps a lot. I was actually using a horrific FOR loop to copy the vars :0

Thanks again,

Ahhhk!

5. What data[2] and data[5] store are just reference of arrays.

So, in this case, swap the reference should be enough. Create a new copy is not necessary.

var temp=data[2];
data[2]=data[5];
data[5]=temp;

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•

 » Home » Movies » Tutorials » Submissions » Board » Links » Reviews » Feedback » Gallery » Fonts » The Lounge » Sound Loops » Sound FX » About FK » Sitemap

Click Here to Expand Forum to Full Width