0

I have a multidimensinal array containing a list of pairs of coordinates:

var coordinates = [
[
    16.383223226146004,
    48.21122334186088
],
[
    16.384753966103307,
    48.211128793925674
],
[
    16.384923422642906,
    48.211127770652936
],
[
    16.38575514277135,
    48.21122830416087
]...

What is the most performant option to switch the coordinate pairs around for all the entries in the array. The list of coordinates can be very long, so I'm looking for a fast working solution.

Expected result:

coordinates = [
[
    48.21122334186088,
    16.383223226146004
],
[
    48.211128793925674,
    16.384753966103307
],
[
    48.211127770652936
    16.384923422642906,
],
[
    48.21122830416087,
    16.38575514277135
]...
1
  • The most performant option probably is to change the access-methods/-indizes. Commented Aug 3, 2014 at 16:46

2 Answers 2

3

Use Array reverse function

coordinates.forEach(function (coordinate) {
    coordinate.reverse();
})
Sign up to request clarification or add additional context in comments.

1 Comment

You don't need the coordinate = here as reverse() is in-place.
2

What is the most performant option to switch the coordinate pairs around for all the entries in the array!

Generally speaking the fastest is usually the simplest, regular loops and just setting the array indices

for (var i=coordinates.length; i--;) {
    var temp = coordinates[i][0];
    coordinates[i][0] = coordinates[i][1];
    coordinates[i][1] = temp;
}

Here's a JSPerf to test different methods

http://jsperf.com/switch-elements

It's about 95% faster than forEach and reverse

jsperf

That's a huge difference, while this code changes the indices in an array with 1000 arrays almost 500k times, the code using forEach and reverse, only executes 17k times.

3 Comments

You can do [coordinates[i][0], coordinates[i][1]] = [coordinates[i][1], coordinates[i][0]] to achieve the same switching effect. Not sure about the efficiency, though.
@Awesomeness01 - Yes, today destructuring is an option, Back in 2014 it wasn't.
Oops, didn't see the date, my bad. So used to it that it seems like it always was this way.

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.