Removing an item from an array while also updating one of its attributes in JavaScript

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!

Answer №1

If you want to make a simultaneous change, consider utilizing a filter:

const trips = [
    {id: 0, destination: "New York", origin: "Barcelona", price: 700, layover: false},
    {id: 1, destination: "Los Angeles", origin: "Madrid", price: 1100, layover: true},
    {id: 2, destination: "Paris", origin: "Barcelona", price: 210, layover: false},
    {id: 3, destination: "Roma", origin: "Barcelona", price: 150, layover: false},
    {id: 4, destination: "London", origin: "Madrid", price: 200, layover: false},
    {id: 5, destination: "Madrid", origin: "Barcelona", price: 90, layover: false},
    {id: 6, destination: "Tokyo", origin: "Madrid", price: 1500, layover: true},
    {id: 7, destination: "Shangai", origin: "Barcelona", price: 800, layover: true},
    {id: 8, destination: "Sydney", origin: "Barcelona", price: 150, layover: true},
    {id: 9, destination: "Tel-Aviv", origin: "Madrid", price: 150, layover: false},
];

const flightID = 4;
let counter = 0;

const result = trips.filter((trip, index) => {
    const difference = trip.id !== flightID;
    counter += difference ? 0 : 1;
    trip.id -= counter;
    return difference;
});

console.log(result);

const trips = [
{id: 0, destination: "New York", origin: "Barcelona", price: 700, layover: false},
{id: 1, destination: "Los Angeles", origin: "Madrid", price: 1100, layover: true},
{id: 2, destination: "Paris", origin: "Barcelona", price: 210, layover: false},
{id: 3, destination: "Roma", origin: "Barcelona", price: 150, layover: false},
{id: 4, destination: "London", origin: "Madrid", price: 200, layover: false},
{id: 5, destination: "Madrid", origin: "Barcelona", price: 90, layover: false},
{id: 6, destination: "Tokyo", origin: "Madrid", price: 1500, layover: true},
{id: 7, destination: "Shangai", origin: "Barcelona", price: 800, layover: true},
{id: 8, destination: "Sydney", origin: "Barcelona", price: 150, layover: true},
{id: 9, destination: "Tel-Aviv", origin: "Madrid", price: 150, layover: false},
];

const flightID = 4;
let counter = 0;

const result = trips.filter((trip, index) => {
const difference = trip.id !== flightID;
counter += difference ? 0 : 1;
trip.id -= counter;
return difference;
});

console.log(result);

Answer №2

To meet this specific requirement, you can easily use the Array#filter method in combination with the Array#map method.

Take a look at this interactive demonstration below:

let flights = [
  { id: 0, to: "New York", from: "Barcelona", cost: 700, scale: false },
  { id: 1, to: "Los Angeles", from: "Madrid", cost: 1100, scale: true },
  { id: 2, to: "Paris", from: "Barcelona", cost: 210, scale: false },
  { id: 3, to: "Roma", from: "Barcelona", cost: 150, scale: false },
  { id: 4, to: "London", from: "Madrid", cost: 200, scale: false },
  { id: 5, to: "Madrid", from: "Barcelona", cost: 90, scale: false },
  { id: 6, to: "Tokyo", from: "Madrid", cost: 1500, scale: true },
  { id: 7, to: "Shangai", from: "Barcelona", cost: 800, scale: true },
  { id: 8, to: "Sydney", from: "Barcelona", cost: 150, scale: true },
  { id: 9, to: "Tel-Aviv", from: "Madrid", cost: 150, scale: false }
];

flights = flights.filter(({ id }) => id !== 4).map((obj, index) => {
    obj.id = index;
  return obj;
});

console.log(flights)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing Express 4, create a fresh route within an app.use middleware

I'm currently working on an express nodejs app where I am attempting to implement "dynamic routes" within another route. Here is what I have: .... app.use('/test/:id', function(req,res,next) { app.use('/foo', sta ...

A JointJS element with an HTML button that reveals a form when clicked

How do I bind data to a cell and send it to the server using the toJSon() method when displaying a form on the addDetail button inside this element? // Custom view created for displaying an HTML div above the element. // ---------------------------------- ...

Guide on utilizing JavaScript to modify the attribute of a chosen web element with Selenium WebDriver in Java

I am seeking a way to utilize Javascript in order to set attributes for the selected element on a webpage. After some research, I have discovered two methods for achieving this with Javascript: Method 1 WebDriver driver; // Assigned elsewhere Jav ...

Switch Focus and Collapse Submenus upon Menu Click in Recursive React Menu

I've created a dynamic menu system in React using Material-UI that supports recursion for submenus. I'm aiming to implement the following features: 1. When a menu item is clicked, all other open submenus should close and focus on the clicked men ...

When the page is loaded, populate FullCalendar with events from the model

On page load, I am attempting to populate events with different colors (red, yellow, green) on each day of the calendar. Here is a simple example showcasing events for three days: https://i.sstatic.net/YzJ4E.png I have data in a model that indicates the ...

Is it possible to share an .ics file using SparkPost in a Node.js environment?

Attempting to generate an i-cal event and link it to a sparkpost transmission in the following manner: const event = cal.createEvent({ start: req.body.a.start, end: req.body.a.end, summary: req.body.a.title, description: req.body.a.body, ...

Animating CSS when closing a modal box

I followed the instructions from a tutorial on W3Schools here to create this code. The "open model" button triggers the modal to open with a smooth CSS animation, which looks great. However, when I click the close button, the modal abruptly closes without ...

Top method for utilizing jQuery to locate, sift through, and implement CSS classes

Let's consider the following scenario: <span class="foo">7</span> <span class="foo">2</span> <span class="foo">9</span> We want to assign a CSS class of 'highest' to 'span.foo' with value great ...

Issue encountered while trying to render an item from a state array in React

I encountered an issue with retrieving state data within the render function. Everything seems to work fine and displays the array when I utilize console.log(items) However, attempting to access the first item from the array results in an error console. ...

Passport appears to be experiencing amnesia when it comes to remembering the user

After extensive research online, I have yet to find a solution to my issue. Therefore, I am reaching out here for assistance. I am currently working on implementing sessions with Passport. The registration and login functionalities are functioning properl ...

Utilizing the setNetWorkConditions function in webdriverjs for Chrome

Is there a way to properly utilize the webdriverjs setNetworkConditions() method as outlined in the official documentation? This is what my code looks like: const chromeCapabilities = webdriver.Capabilities.chrome() const chromeOptions = { ...

Steady Navigation Bar in Javascript without Bouncing

While experimenting with a fixed navigation bar, I've encountered an issue where the content below jumps up on the page when the navigation bar "fixes" itself to the top of the screen. You can check out the JSFiddle I've been working on for refer ...

Having trouble with VueJS ref not preventing the default form action on submit?

Within my <script> tag, I currently have the following code: render(createElement) { return createElement("form", {ref: "formEl" , on: {submit: this.handleSubmit} }, [ <insert create form inputs here> ]); } handleSubmit(e) { ...

Invoke a directive's function on a page by utilizing ng-click in AngularJS

Is there a way to call a function from a directive in an HTML page like index using ng-click? Below is the code for my directive: $scope.moreText = function() { $(".showMore").append(lastPart); }; html: <a ng ...

I am currently seeking a way to validate if a variable corresponds to the choice made in the dropdown menu. Any suggestions on how to accomplish this task?

I have put together a simple drop down menu. My goal is to grab the currently selected value from the drop down list, store it in a variable, and display it in the console. The ultimate objective is to compare that variable with another one to determine if ...

mention a Vue.js component computed property that points to a specific DOM element

Is there a way to access the DOM element that initiated a method inside a Vue component computed property? For example: <template> <img :src="getUrl" class="image1"/> <img :src="getUrl" class="image2"/> </template> <scri ...

Conflicting styles arise when using the makeStyles function from Material UI with imported

In working on a React component library using create-react-library, I have incorporated basic components that utilize Material UI components and the material UI hook-based styles pattern. For example (in a simplified form): // LibraryComponent.js const u ...

What is the best way to include an "average" line in a nvd3.js Stacked Area Chart?

My Stacked Area Chart is up and running smoothly using NVD3.js. You can view it in action on this working jsfiddle link. var volumeData = [{"key":"Hit","values":[[1.3781628E12,12],[1.3782492E12,9],[1.3783356E12,9],[1.378422E12,4],[1.3785084E12,2],[1.37859 ...

Using Vue.js to set both v-model and v-bind:value on one input element

I have a React component that has a form for submitting user information. The main issue I'm facing is setting a default value in the input field. When the page loads, I want the input field to display the user's existing email address by defaul ...

Pagination in Datatables

Here is the code snippet I am working with: $('#ldap-users, #audit-users').dataTable({ "sDom": "<'row'<'span6'l><'span6'f>r>t<'row'<'span6'i><'span6'p& ...