Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

174
Visualizações
How to swap values of an array? Javascript

I am using Leaflet and I am trying to create a polyline and marker points but it gives opposite lat and long so I have to swap them. Creating a marker is easy because it only has one pair of lat and long but creating a polyline is complicated because has a lot of points.
Below is what I am currently using to swap lat and long for marker points.

var splitObj = objVal.toString().split("],[");
var latlng = splitObj.map(function(x)
    {
        var couple= (/\d+.\d+, \d+.\d+/g).exec(x).toString();
        var splitted = couple.split(", ");
        return "["+splitted[1]+","+splitted[0]+"]";
    });
latlng.join();

Result:

['[[a, b], [c, d], [e, f]]'] // this is the objVal
expectation:
['[[b,a], [d,c], [f,e]]']
reality:
['[b,a]']

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

map over the array it and, for each inner array, return a new array after swapping the elements around.

const data = [[124.432841, 8.3963], [124.496898, 8.3963], [124.571937, 8.40898]];

const result = data.map(arr => {
  return [arr[1], arr[0]];
});

console.log(result);

about 4 years ago · Juan Pablo Isaza Relatório

0

Assuming the input is a string of nested-array-like values, the below solution may help in transforming/swapping latitude-longitude values.

Code Snippet

const inpVal = ['[[a, b], [c, d], [e, f]]'];

// helper method to strip first & last char of a string
const stripFirstLast = s => s.slice(1, s.length - 1);

// helper method to swap lat & longitutde values
const swapLatLon = ([lat, lon]) => [lon, lat];

// place holder to safe-keep value of input
const tmp = stripFirstLast(inpVal[0])
  .replaceAll('], ', '] | ')
  .split(' | ');

// calculate the result
const res = ["[" +
  tmp.map(
    x => '[' +
    swapLatLon(
      stripFirstLast(x).split(', ')
    ).join(', ') +
    ']'
  ).join(', ') +
  "]"
];

// console-log to validate/verify
console.log(
  'input: ', inpVal,
  '\nresult: ', res
);

Explanation

Comments inline explain the approach used.

Swap with actual values (and not string)

This is an almost-exact replica of Andy's solution/answer with only one change instead of handling the inner array as arr, the iterator directly accesses the lat & lon values. I think it makes the solution a little more easier to read.

// Previous solution where the orig data was not taken as a string
const swapLoLa = arr => arr.map(([lon, lat]) => [lat, lon]);
const orig = [[124.432841, 8.3963], [124.496898, 8.3963], [124.571937, 8.40898]];
console.log(
  'orig arr: ', orig,
  '\nswapped arr: ', swapLoLa(orig)
);

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda