Home > front end >  Rearrange array elements from the updated indexing array
Rearrange array elements from the updated indexing array

Time:06-16

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()

CodePudding user response:

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);

CodePudding user response:

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.

  • Related