Is it possible to utilize Vue's splice method within a forEach loop in order to delete multiple elements at

I am currently working on an image grid in array form. I am trying to implement a multi-deletion functionality.

When a checkbox for each image in the grid is checked, I store the selected image's index in an array called selectedImages.

Upon clicking the delete button, I have written a remove method as shown below:

     removeSelectedImages() {
        console.log(this.additionalPhotos);  //ImageGrid array
        console.log(this.selectedImages);  //selectedImages array

        this.selectedImages.sort().reverse();
         this.selectedImages.forEach((selectedImageIndex, index) => {
        this.additionalPhotos.splice(selectedImageIndex, 1);
        this.selectedImages.splice(index, 1);
        });
      },

The issue I'm facing is that the splice function only works once. Initially, I thought it was because of how indexes were resetting and causing issues. I tried reversing the selected images array based on their values but the problem still persists.

For example, if I select image 2 and 1, only image 2 gets deleted when the splice function is used. It doesn't enter the loop the second time. However, if I remove the splice function, it runs twice.

If you have any suggestions or best practices for solving this issue, please let me know. Thank you!

Answer №1

If you want to easily exclude deleted pictures:

let extraImages = [{fileSrc: 'aa', fileName: '1.png'}, {fileSrc: 'bb', fileName: '2.png'}, {fileSrc: 'cc', fileName: '3.png'}, {fileSrc: 'dd', fileName: '4.png'}, {fileSrc: 'ee', fileName: '5.png'}, {fileSrc: 'ff', fileName: '6.png'},]
const removedImages = [2,4]
function eraseSelectedImages() {
  extraImages = extraImages.filter((_, idx) => {
    return !removedImages.includes(idx)
  })
}
eraseSelectedImages()
console.log(extraImages)

Answer №2

handleImageRemoval() {
   console.log(this.additionalPhotos);  //Displaying ImageGrid items
   console.log(this.selectedImages);  //List of selected images

   this.selectedImages.sort()
   let index
   for (index=this.selectedImages.length-1; index>=0; index--) {
      this.additionalPhotos.splice(this.selectedImages[index],1)
   } 
   this.selectedImages=[]    
}

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

Sending a nested route broadcast in VueJS 2

Here are the routes I am using: <script> routes = [ { path: '/', component: Home, children: [{ path: 'nested1', name: 'nested1', component: Nested1, }, { ...

Tips for creating a smooth transition effect using CSS/JavaScript pop-ups?

Looking for some assistance in creating a CSS pop-up with a touch of JavaScript magic. I've managed to trigger the pop-up box by clicking a link, and while it's visible, the background fades to grey. But I'm struggling to make the pop-up fad ...

Show information in tooltips across several rows

Within my Vue.js component, I am attempting to craft a custom tooltip text that consists of multiple lines. <div class="toolTip"> Shift ('+i+') </div> <div class="hide"> <div class="w-full"&g ...

What is the best method for saving and accessing a user-entered date using session storage?

https://i.sstatic.net/I8t3k.png function saveDateOfBirth( dob ) { sessionStorage.dateOfBirth = dob; } function getDateOfBirth() { document.getElementById("confirm_dob").textContent = sessionStorage.dateOfBirth; } function pr ...

I could really use some assistance with this script I'm working on that involves using ($

Using Ajax for Form Submission: $.ajax({ url: 'process.php', type: 'post', data: 'loginName=' + $("#loginName").val() + 'loginPass=' + $("#loginPass").val(), dataType: 'json', success: func ...

Generating a dynamic form by utilizing a JavaScript JSON object

I need assistance with creating an html form based on a JSON object’s properties. How can I target multiple levels to generate different fields and also drill down deeper to access field details? I am open to suggestions for alternative formats as well. ...

Guidelines for attaching a div to the bottom of a page?

I have a navigation menu inside div.wrapper, and I am trying to make the div.wrapper stick to the footer. <div class="wrapper"> <div id="menu"> <ul> <li>1.</li> <li>2.</li> ...

NodeJS Socket not transmitting file after connection with client

Having scoured the depths of various resources, including SO and Google, I have hit a roadblock. I am struggling to understand why the socket is failing to capture the uploaded file via the form; it simply stops after connecting. When I check the console, ...

Exploring the automated retrieval of data from arrays in Java objects: A comprehensive guide

My goal is to automatically create Java objects from JSON data obtained from a REST API. The JSON array contains properties of different shops, and I aim to generate one object per shop with all its respective properties. The following code helped me achi ...

Switching to fullscreen mode and eliminating any applied styles

I'm trying to enable fullscreen mode with a button click. I've added some custom styles when the window enters fullscreen, however, the styles remain even after exiting fullscreen using the escape key. The styles only get removed if I press the e ...

Using .get methods with jQuery's .on

I need to retrieve the tag name of the element that is clicked inside an li when the user interacts with it. The li element gets dynamically added to the HTML code. I have implemented the following code, but unfortunately, it does not seem to be functionin ...

The method for retrieving and entering a user's phone number into a text field upon their visit

Objective: To enhance the user experience by automatically filling in the phone number input field when a mobile user views the page, making it easier to convert them into leads. A privacy policy will, of course, be in place. This page will offer a promo ...

The vuex 3 state variable is currently undefined

Currently, I am in the process of setting up an application that utilizes Vue 2.5.2 and Vuex 3.0.1. Despite my efforts, there is one persistent warning that continues to appear: [Vue warn]: Error in render: "TypeError: _vm.product is undefined" The var ...

Rendering basic JSON data from the console to an HTML page using Angular

I have been utilizing openhab for sensor monitoring. To extract/inject the items(things), sensor properties, and room configuration through a web interface, I am making use of openhab's REST queries which can be found here - REST Docs. Wanting to cre ...

Tips for connecting to multiple items in an md-select element from within a directive

Looking to develop a straightforward directive that displays either a textbox or dropdown based on whether an array is provided for the model property on the scope. Any value other than explicitly setting false in the directive markup such as multiple="fa ...

Toggle Form Section Visibility

I am working on a table with five rows that have upload buttons. Each time I submit a row, the page refreshes, but I want to hide all but one row at a time. When the first submit button is clicked, it should show the next row and hide the previous ones. Th ...

jQuery - Show or hide content with a toggle action

Is there a way to toggle the text on a button once certain content is visible? Can the content be hidden if the button is clicked again? To better illustrate, check out this example: JSFiddle I am looking to switch the button text from 'View content ...

Vanilla JavaScript error: Unable to access property

I am working on implementing a header with a logo and navigation that includes a menu toggle link for smaller viewports. My goal is to achieve this using Vanilla JS instead of jQuery. However, when I click on the menu toggle link, I encounter the followin ...

MongoDB table collections (table names in other databases)

After setting up my express server to connect to mongodb, I encountered an issue despite everything working fine initially. I created a collection in my mongodb called projects (plural form). In my project.model.js file, I defined the model as follows: c ...

What's causing my variables to be returned as null in the alerts?

Why am I receiving null values when alerting my variables? I'm attempting to pass a string stored in a variable from an external JavaScript file back to the main page using alerts. Initially, I suspected that the JavaScript was not fetching data cor ...