I am facing a challenge with this list of objects:
const flights = [
{ id: 00, to: "New York", from: "Barcelona", cost: 700, scale: false },
{ id: 01, to: "Los Angeles", from: "Madrid", cost: 1100, scale: true },
{ id: 02, to: "Paris", from: "Barcelona", cost: 210, scale: false },
{ id: 03, to: "Roma", from: "Barcelona", cost: 150, scale: false },
{ id: 04, to: "London", from: "Madrid", cost: 200, scale: false },
{ id: 05, to: "Madrid", from: "Barcelona", cost: 90, scale: false },
{ id: 06, to: "Tokyo", from: "Madrid", cost: 1500, scale: true },
{ id: 07, to: "Shangai", from: "Barcelona", cost: 800, scale: true },
{ id: 08, to: "Sydney", from: "Barcelona", cost: 150, scale: true },
{ id: 09, to: "Tel-Aviv", from: "Madrid", cost: 150, scale: false },
];
When deleting an object, I want the subsequent object IDs to be adjusted accordingly by subtracting 1.
For instance, if I delete the fifth object (id: 04
), I want the IDs to follow a sequence from 0 to 8 instead of jumping from 0 to 9 and skipping 4 (0, 1, 2, 3, 5, 6, 7, 8, 9).
This is my current code snippet:
let flightIdToDelete = 04;
for (let i = 0; i < flights.length; i++) {
if (flightIdToDelete === flights[i].id) {
delete flights[i];
}
}
/* The updated array would look like this:
const flights = [
{ id: 00, to: "New York", from: "Barcelona", cost: 700, scale: false },
{ id: 01, to: "Los Angeles", from: "Madrid", cost: 1100, scale: true },
{ id: 02, to: "Paris", from: "Barcelona", cost: 210, scale: false },
{ id: 03, to: "Roma", from: "Barcelona", cost: 150, scale: false },
{ id: 05, to: "Madrid", from: "Barcelona", cost: 90, scale: false },
{ id: 06, to: "Tokyo", from: "Madrid", cost: 1500, scale: true },
{ id: 07, to: "Shangai", from: "Barcelona", cost: 800, scale: true },
{ id: 08, to: "Sydney", from: "Barcelona", cost: 150, scale: true },
{ id: 09, to: "Tel-Aviv", from: "Madrid", cost: 150, scale: false },
]; */
I believe iterating through object IDs starting from the deleted one and reducing them by 1 should work, but I'm uncertain about how to proceed.
Your assistance would be greatly appreciated!