Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

175
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!