简体   繁体   中英

javascript: switch elements of each element in multidimensional array

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
]...

Use Array reverse function

coordinates.forEach(function (coordinate) {
    coordinate.reverse();
})

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM