Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

176
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda