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

177
Visualizações
Rearrange array elements from the updated indexing array

I don't really know how to explain my problem so sorry for the title.

I have three JavaScript arrays:

//indexing array
originalData = ['data1', 'data2', 'data3']

//target array
originalPos = ['50 a', '80 b', '31 c']

//updated indexing array
newData = ['data1', 'data3', 'data2']

With that array, I want to get the new order of the originalPos array by using newData array like this :

originalPos = ['50 a', '31 c', '80 b']

The goal is to be able to change the position of my waypoints in the Leaflet Routing Machine using L.routing.machine.spliceWaypoints()

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

0

You can rearrange by finding the position of every element of originalPos in originalData and with that respective position you can push the element from newData into the result array.

Assuming there is no duplicate data within all three arrays

const originalData = ['data1', 'data2', 'data3']
const originalPos = ['50 a', '80 b', '31 c']
const newData = ['data1', 'data3', 'data2']

const newPos = newData.map(n => n && originalPos[originalData.indexOf(n)]);

console.log(newPos);

about 4 years ago · Juan Pablo Isaza Relatório

0

Take note of the indexes at which the original keys occur in originalData (using a Map or plain object). Then map the keys in the new order (newData) to the index in that mapping, and take the value at that index in the input data (originalPos):

const originalData = ['data1', 'data2', 'data3'];
const originalPos = ['50 a', '80 b', '31 c'];
const newData = ['data1', 'data3', 'data2'];

const map = new Map(originalData.map((val, i) => [val, i])); 
const result = newData.map((val, i) => originalPos[map.get(val)]);
console.log(result);

NB: the use of the map will avoid a scan in the first array at each iteration (like with indexOf), so giving it a better time complexity.

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