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

103
Visualizações
Create an associative array from for loop results in javascript

I have a form that calculates mileage from 4 destinations to one single origin. When submitted, I can display the text that shows the origin and the distance to each destination on a new line, for example:

Margate, UK to Coventry, UK: 177 mi in 3 hours 13 mins Brighton, UK to Coventry, UK: 158 mi in 2 hours 41 mins Bristol, UK to Coventry, UK: 108 mi in 1 hour 49 mins Birmingham, UK to Coventry, UK: 21.8 mi in 31 mins

I want to create an array of this information so I can call it in other functions. For example, I just want the Destination and the miles, so something like this:

{"Margate, UK" => 177, "Brighton, UK" => 158, "Bristol, UK" => 108, "Birmingham, UK" => 21.8}

Here is the code I use to make the for loop:

function calcDistance(response, status) {
  if (status != google.maps.DistanceMatrixStatus.OK) {
    alert('Error was: ' + status);
  } else {
    var origins = response.originAddresses;
    var destinations = response.destinationAddresses;

    for (var i = 0; i < origins.length; i++) {
      var results = response.rows[i].elements;
      for (var j = 0; j < results.length; j++) {

    outputDiv.innerHTML += origins[i] + ' to ' + destinations[j]
                + ': ' + results[j].distance.text + ' in '
                + results[j].duration.text + '<br>';

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

0

You can try making an array const distances = [] and then push into it the desired information in the inner for loop

...
var results = response.rows[i].elements;
for (var j = 0; j < results.length; j++) {
  distances.push([origins[i], results[j].distance.text])
  ...
}

or you could extract the information from the submitted form text using regex

const distinations =
  'Margate, UK to Coventry, UK: 177 mi in 3 hours 13 mins Brighton, UK to Coventry, UK: 158 mi in 2 hours 41 mins Bristol, UK to Coventry, UK: 108 mi in 1 hour 49 mins Birmingham, UK to Coventry, UK: 21.8 mi in 31 mins'

const cities = distinations.match(/\b(?:(?!Coventry)\w)\w+, \w+/g)
const distances = distinations.match(/(?<=: )\d+/g)

const result = []
for (let index in cities) {
  const city = cities[index]
  const distance = distances[index]
  result.push({
    city,
    distance
  })
}

console.log(result)

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