0

I have an array like this - (i do not know the length of this array in advance)

data: [[3, 1], [1, 1], [5, 1], [6, 1], [25, 1], [8, 2], [2, 3]]

how i can swap it so it becomes like this:

data: [[1, 3], [1, 1], [1, 5], [1, 6], [1, 25], [2, 8], [3, 2]]

Thanks!

2
  • 1
    Smells like homework. If it is, please tag it as such. Commented Apr 9, 2012 at 19:15
  • wish it was! ..i will accept Xander's very quick answer Commented Apr 9, 2012 at 19:30

3 Answers 3

4

Each element is an array, so you can apply reverse on it.

for(i = 0; i < data.length; i++) data[i].reverse();
Sign up to request clarification or add additional context in comments.

Comments

2
var i, temp;

for(i = 0; i < data.length; i++) {
    temp = data[i][0];

    data[i][0] = data[i][1];
    data[i][1] = temp;
}

Comments

0
var data = [[3, 1], [1, 1], [5, 1], [6, 1], [25, 1], [8, 2], [2, 3]];
data = data.map(function(x){ // loop though all elements
    return x.reverse(); // reverse each array
});

Arary.map should work on all modern browsers (by that I mean you need Chrome, Firefox, Safari, Opera, or IE9+).

EDIT: Since Array.reverse will mutate the array, you can also do this:

var data = [[3, 1], [1, 1], [5, 1], [6, 1], [25, 1], [8, 2], [2, 3]];
data.forEach(function(x){ // loop though all elements
    x.reverse(); // reverse each array
});

Array.forEach works in the same "moden" browsers, that .map works in.

1 Comment

It seems that .forEach is much slower than a normal for loop

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.