I have two arrays, mapsOrder and mapsData, containing objects:
let mapsOrder = [1,2,1,3];
let mapData = [
{
id: 1,
gates: [
{
toId: 2,
coords: {
x: 2,
y: 42
}
},
{
toId: 3,
coords: {
x: 9,
y: 4
}
}
]
},
{
id: 2,
gates: [
{
toId: 1,
coords: {
x: 6,
y: 5
}
}
]
},
{
id: 3,
gates: [
{
toId: 1,
coords: {
x: 2,
y: 1
}
}
]
}
]
The goal is to loop through the mapsOrder
array where its values correspond to ids in mapData
, and assign gates to the next map.
During each iteration:
- When index is 1, current map is 1, next map is 2, and gates to next are
coords: { x: 2, y: 42 }
- When index is 2, current map is 2, next map is 1, and gates to next are
coords: { x: 6, y: 5 }
- When index is 3, current map is 1, next map is 3, and gates to next are
coords: { x: 9, y: 4 }
- When index is 4, current map is 3, next map is 1, and gates to next are
coords: { x: 2, y: 1 }
For the last iteration, the next map will be the first one in the mapsOrder
array. I attempted to achieve this by determining the id of the next map using the following code snippet:
for(let i = 0; i < mapsOrder.length; i++) {
let nextMap;
let currentMapId = mapData[mapsOrder[i] - 1].id;
if(i === mapsOrder.length - 1) {
nextMap = mapData[0].id
} else {
nextMap = mapData[mapsOrder[i]].id;
}
console.log('Current map is: ', currentMapId, 'and the next map id is:', nextMap)
console.log('break-----')
}
However, this code returns incorrect IDs. You can view a live demo here.