Issue when attempting to delete a particular item from a list

Struggling with removing a specific element from a list.

Despite using the splice method to cut out an element at a specific point, it always ends up removing the last one instead.

<template>
  <div>
    <v-row>
      <v-col>
        <h3>Steam</h3>
        <v-btn class="mx-2" fab dark color="purple" @click="addCardSteam">
          <v-icon dark>mdi-plus</v-icon>
        </v-btn>
      </v-col>
      <v-col>
        <h3>Map 2D et 3D</h3>
        <v-btn class="mx-2" fab dark color="cyan" @click="addCardMaps">
          <v-icon dark>mdi-plus</v-icon>
        </v-btn>
      </v-col>
      <v-col>
        <h3>Youtube</h3>
        <v-btn class="mx-2" fab dark color="red" @click="addCardYT">
          <v-icon dark>mdi-plus</v-icon>
        </v-btn>
      </v-col>
    </v-row>
    <v-row>
      <v-col>
        <YTCard v-for="(card, index) in Youtube"
        v-bind:key="index"
        v-model="card.deleted"
        @input="UpdateYT"></YTCard>
      </v-col>
    </v-row>
  </div>
</template>

<script>
import YTCard from './YoutubeCard'

export default {
  data: () => ({
    Steam: [],
    Maps: [],
    Youtube: [],
    YT: 0
  }),
  methods: {
    UpdateYT: function () {
      console.log('Youtube => ', this.Youtube)
      this.Youtube = this.Youtube.filter(yt => !yt.deleted)
    },
    addCardYT: function (num) {
      this.YT = this.YT + 1
      this.Youtube.push({deleted: false, num: this.YT})
    },
    addCardMaps: function () {
      this.Maps.push({deleted: false})
    },
    addCardSteam: function () {
      this.Steam.push({deleted: false})
    }
  },
  components: {
    YTCard
  }
}
</script>

<style scoped>
</style>

Tried numerous approaches but still ends up deleting the final element.

Any insights or suggestions are greatly appreciated.

Updated the Question for clarity.

Answer №1

When iterating over an array using the index i, and making changes to the array during iteration, it's highly likely to introduce bugs.

Consider this alternative approach:

var RandomClass = {
  // Here is how data gets updated
  Youtube: [],

  UpdateYT: function () {
      // console.log('Youtube => ', this.Youtube)
      this.Youtube = this.Youtube.filter(yt => !yt.deleted);
  },

  addCardYT: function (num) {
    this.Youtube.push({deleted: false, num:num})
  },
}

RandomClass.addCardYT(1);
RandomClass.addCardYT(2);
console.log(RandomClass.Youtube);
RandomClass.Youtube[0].deleted = true;
RandomClass.UpdateYT();
console.log(RandomClass.Youtube);

[edit]

If you still prefer to iterate using i and delete elements as you go, a better approach would be to start at the end of the array and move backwards.

Answer №2

const videos = [
    { id: 1, removed: false },
    { id: 2, removed: true },
    { id: 3, removed: false },
    { id: 4, removed: true },
    { id: 5, removed: true },
    { id: 6, removed: false },
];

console.log('Initial state of videos array:', videos);

const updateVideos = () => {
    let i = videos.length - 1;
    while (i >= 0) {
        if (videos[i].removed) videos.splice(i, 1);
        i--;
    }
}

updateVideos();

console.log('Updated state of videos array:', videos);

Note: As pointed out by TKoL, iterating over an array can lead to bugs when removing consecutive elements. Reversing the iteration should solve this issue.

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

What are the steps to programmatically click a JavaScript button with Selenium and Python?

Imagine there is a button on a webpage that looks like this: <input type="submit" name="next_btn" value="Next" onclick="gonext();" id="btnNext"> When manually clicked, it takes approximately 3-6 seconds for the page to reload and show new content. ...

ReactJs - Minimizing unnecessary re-renders caused by context changes - A step-by-step solution

I've been working on my website at , and I came across an issue that I can't seem to solve. I created a custom cursor along with a CursorContext to change its state on hover, but every time the context changes, all components in my app are re-ren ...

The npm run dev command is not functioning properly within the HackerNews example on Vue.js

I attempted to launch the vue-hackernews-2.0 demo from the vuejs' github repository The setup section provides instructions on how to set up the project: # install dependencies npm install # or yarn # run in dev mode, with hot reload at localhost:8 ...

The prop "cellClass" has failed the type check. It was expected to be a String containing the value "[object Object]", but an Object was provided instead

I'm attempting to conditionally apply a CSS class to a row (all b-table-column) within a b-table, like so: <b-table-column class="is-unselectable" :cell-class="{ 'has-pointer-cursor': props.row.url != null }" field="version" la ...

Using Tinymce to automatically send form on blur action

Attempting to trigger form submission upon blur event in Tinymce, but encountering difficulties. tinymce.init({ selector: 'textarea.html', menubar:false, force_br_newlines : true, force_p_newlines ...

Error: Unable to submit data as the function this.submitData is not recognized

Having trouble calling an async function in the mounted() lifecycle hook of Vue.js? Keep getting the error message: Uncaught TypeError: this.submitData is not a function. Here's the code snippet in question: <template> <section class=&quo ...

Ten instances of $digest() being triggered upon the implementation of custom filters

I am struggling with the following angular markup: <tr ng-repeat="dia in dias"> <td>{{ dia[0].fecha }}</td> <td ng-repeat="bloque in bloques"> <div ng-repeat="hora in dia|soloBloque:bloque|sacarHoras"> ...

Generating random numbers in JavaScript using the Math.random() method and incorporating them

Looking to display 2-3 .mp4 files randomly on each page load? Consider using JavaScript for this task. Here's a snippet of code that you can use as a starting point: #vid { position: fixed; min-width: 100%; min-height: 100%; opacity: ...

Using React Native to share API and passing a Base64 string in place of an image when sharing to WhatsApp

I am facing difficulties in sharing a base64 image on WhatsApp. On both iOS and Android, the actual base 64 code is shared instead of the image. When I try to use iMessage or Email on iOS, the base64 images are converted and displayed correctly. However, ...

The react transition group fails to add the necessary CSS classes to the specified div

Regardless of whether I utilize React transition group, Tailwind, pure CSS, or any other framework, no transitions seem to occur when I structure my simple component in the following manner. I have experimented with various frameworks, but the outcome rema ...

The issue of React props malfunctioning within a for loop is causing some trouble

When passing the rating as a prop to the Star Rating component, I can access the rating value in the StarRating function. However, whenever it enters the for loop, the rating becomes invisible. import React from 'react' const StarRating = ({ rat ...

Oops! The data seems to be missing

My script periodically fetches new ads every 10 seconds, but I encountered an error. function getNewAds(){ var newer ; // Retrieve old value from 'data-value' attribute var oldVal = $("#new_data").data('value'); $.ajax( ...

Encountering issues with Electron Vue scaffolding

Upon setting up the electron-vue scaffold through the vue-cli with vue init simulatedgreg/electron-vue, I used yarn followed by yarn run dev to start the application. However, default errors started popping up: ? Electron ------------------- Debugger l ...

"An issue arises where the bokeh plot fails to render when generating a

I have been working on embedding a bokeh plot within a webpage served by a simple Flask app. I am using the embed.autoload_server function that I found in the bokeh embed examples on github. While everything seems to be functioning correctly on the Python ...

Using JSON in JavaScript to handle the click event of ASP.NET buttons

Here is the code that works well for me. I need to execute two different server-side functions, and they can't run at the same time as I have separated them. Default.aspx/AddCart btnUpdate Click Event The issue I'm facing is that the alert box ...

Tips for embedding text into a doughnut chart with primeng/chart.js

Currently tackling a primeng chart project involving the development of a doughnut chart within angular. The task at hand is to display text inside the doughnut chart, aligning with the designated design vision. Referencing the image below for visualizatio ...

Implementing a Vue feature where an object is utilized as the v-model within a select

I am currently working with a select tag that displays an array of objects as its options. Each option only shows the name property of the object. The v-model on the select tag is initially set to one of the object's name properties. My aim is to use ...

Why is `screen` important?

Recent articles in June 2020 discussing "how to utilize react testing library" often showcase a setup similar to the one below: import React from 'react'; import { render, screen } from '@testing-library/react'; import App from '. ...

Creating a JSON Response Using PHP API

I created a basic JSON response to test the functionality of an AJAX request on a mobile device. Using a local domain called test.local, I generated a json response. header("Content-Type:application/json; charset=utf-8"); echo json_encode(array('nam ...

Accessing Google Sheets with the default login information

I have data stored in Google sheets and I am utilizing the Sheets API for Node.js to retrieve this data. To authenticate, I am using Service Account JSON to create a JWTClient. Accessing the data through the Sheets API is functional and everything is runn ...