'Why are split and join results are different?
I used split and join to swap latitude and longitude of the coordinates. I am using leaflet to get the coordinates and as polyline, swapping coordinates works just fine but when I do it using marker, the last digit of the latitude and first digit of longitude is gone
This is the code, as you can see they're just the same code
if (type === 'polyline') {
const res = ["[" +
tmp.map(
x => '[' +
swapLatLon(
stripFirstLast(x).split(', ')
).join(', ') +
']'
).join(', ') +
"]"
];
document.getElementById("polyline").value = res;
} else if (type === 'marker') {
const res = ["[" +
tmp.map(
x => '[' +
swapLatLon(
stripFirstLast(x).split(', ')
).join(', ') +
']'
).join(', ') +
"]"
];
document.getElementById("marker").value = res;
} else {
console.log('__undefined__');
}
This is a sample result for res
Original: [37.0902, 95.7129]
Expectation: [[95.7129, 37.0902]]
Reality: [[95.712, 7.0902]]
Solution 1:[1]
split and join are inverses of each other. It is likely that the issue is elsewhere in the data processing.
In any case, here is a direct one line solution using the data examples that you provided:
x = "[37.0902, 95.7129]"
swapped = "[" + x.slice(1,-1).split(", ").reverse().join(", ") + "]"
Solution 2:[2]
If you only want to swap places of two variables in an array, then use deconstructing.
const tmp = [37.0902, 95.7129]
let [long, lat] = tmp;
let res = [[lat, long]];
let type;
if (type === 'polyline') {
document.getElementById("polyline").value = res;
} else if (type === 'marker') {
document.getElementById("marker").value = res;
} else {
console.log('__undefined__');
}
console.log({tmp})
console.log({res})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | davidvarela_us |
| Solution 2 | Rickard Elimää |
