How to delete the last element of an array in Vue.js

Currently, I'm facing an issue with a filter duplication feature in my code. When I click on the "add filter" button, a duplicated filter is added to the array. However, the problem arises when I try to remove a filter using the cross icon - it always removes the last item from the array instead of the intended one. Below is the code snippet:

<div class="container">

  <div class="jumbotron">
    <div>
      <div class="form-group">
        <input type="text" class="form-control input-sm" id="pref-search">
      </div>
      <div class="form-group">
        <button type="button" class="btn btn-default filter-col btn-sm" v-on:click="addFilter">
          <i class="fa fa-plus-circle" aria-hidden="true"></i> Add filter
        </button>
      </div>
    </div>

    <div v-for="filter in extFilters.filters" style="margin: 10px 0">
      <div class="form-group">
        <input type="text" class="form-control input-sm" id="pref-search">
      </div>
      <div class="form-group">
        <button type="button" class="btn btn-default filter-col btn-sm" v-on:click="addFilter">
          <i class="fa fa-plus-circle" aria-hidden="true"></i> Add filter
        </button>
        <span v-on:click="removeFilter(filter)"><i class="fa fa-times" aria-hidden="true"></i></span>
      </div>
    </div>
  </div>
</div>

The Vue.js portion of the code is as follows:

var data = {
  'filters': [],
}

// Vue app instance
var app = new Vue({
  // Initial state of the app
  data: {
    extFilters: data,
  },

  // Functions handling data logic
  methods: {
    addFilter: function() {
      this.extFilters.filters.push({
        andor: 'a',
        search_in: '',
        operator: '',
        text: ''
      })
    },

    removeFilter: function(filter) {
      var index = this.extFilters.filters.indexOf(filter);
      this.extFilters.filters.splice(index, 1);
    },
  },
})

// Initialization
app.$mount('.jumbotron')

The issue arises when attempting to remove a specific filter after adding multiple filters. Instead of removing the intended filter, it always removes the last one. I'm seeking assistance for correcting this issue. You can view the problem on jsFiddle. It would be helpful to have the solution provided on jsFiddle as well.

Answer №1

The correct solution can be found at this link: https://jsfiddle.net/mariaczi/hed0ew5o/1/

An important missing step was adding v-model='filter.text' to the text input, causing all filters to appear the same and not work as intended.

Now, everything is functioning as expected.

Trust this information proves helpful to you.

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

I encounter an error in my JavaScript function indicating that it is not defined

let element = document.querySelector("#value"); let buttons = document.querySelectorAll(".btn"); buttons.forEach(function (button) { button.addEventListener("click", function(event){ console.log(event.currentTarge ...

Arranging elements in an array based on specified order string in Swift 3

Need help organizing an array var myArray = ["Dog", "B-1", "C-1", "C-2", "C-3","Home"] according to a specific character string order. For example, if myCustomString = "DC" Input Array: ["Dog","Goat","C-1","C-2","C-3","Home"] Desired Output Array: [ ...

Error: The OrbitControls function is not recognized in THREE.JS

const scene = new THREE.Scene(); const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000); const controls = new OrbitControls(camera); camera.position.set(200, 0, 0); controls.update(); const geometry = new THREE.S ...

Maintain the aspect ratio of an image when placing it in a square container

Looking for a way to create a CSS grid with non-square random sized images? I need help filling all the space inside a fixed size div. Any suggestions? Check out my example: (blue represents the fixed size div and red shows the image inside it) ...

Struggling to set up bcrypt on server for Vuejs 2.6.9/Webpack 4.29.6 project with NodeJS 10.15.3 and NPM 6.4.1 on a Vagrant virtual machine

Struggling to get bcrypt installed all weekend has been a challenge. During this period, I upgraded Node to version 10.15.3 (and npm 6.4.1). One potential solution suggested is to abandon bcrypt and opt for bcryptjs instead. My concern with this suggestio ...

Introducing cutting-edge intellisense for Typescript Vue in VSCode, featuring automatic import functionality specifically designed for the

Currently, I am working on a small project using Typescript and Vue in VSCode. In my setup, I have TSLint, TSLint Vue, Vetur, and Prettier plugins installed. Unfortunately, I am facing an issue with the intellisense "auto import" feature. It does not seem ...

glsify - encountering the error message 'This file type could require a specific loader to be handled'?

Currently, I'm attempting to implement a custom shader following the guidance provided at https://tympanus.net/codrops/2019/01/17/interactive-particles-with-three-js/. I have imported the .frag and .vert files (provided in the link) and replicated the ...

Issue: Unable to access GET request with Express and handlebars

Hello everyone, I'm just getting started with JS/Handlebars and I'm facing an issue trying to display an image from my home.hbs file in VS Code. When I start the server, this is the message I receive: https://i.sstatic.net/wUxB7.jpg Below is th ...

Utilizing Angular 2's *ngFor to conditionally wrap elements can be compared to organizing a layout with three columns in a Bootstrap row, then starting a

Currently I am facing a challenge with using *ngFor and it has me puzzled. My goal is to incorporate UIkit, but the same concept would apply to Bootstrap as well. <div *ngFor="let device of devices" > <div class="uk-child-width-expand@s uk-te ...

Unable to access the current state within an asynchronous function in React.js

I have encountered an issue with updating state in the top-level component (App) and accessing the updated state in an asynchronous function defined within useEffect(). Here are more details: The problem arises when I try to retrieve the state of the cons ...

Tips for finding the displayRows paragraph within the MUI table pagination, nestled between the preceding and succeeding page buttons

Incorporating a Material-UI table pagination component into my React application, I am striving to position the text that indicates the current range of rows between the two action buttons (previous and next). <TablePagination ...

What is the best way to include and transmit multiple records in ASP.NET MVC with the help of jQuery?

Having trouble sending multiple records to the database using JavaScript in ASP.NET MVC? Look no further, as I have the best code that can send data to the controller. However, the file attachment is not being sent along with it. I've tried various m ...

Implementing dynamic keys in a JSON data structure with Node.js

Specifically focused on utilizing Node.js ES6 capabilities. I am currently working on creating a JSON document for insertion into a MongoDB database. The keys for inserting the document will be derived from the input values provided. For instance, Here i ...

Using PHP to convert an array of SQL rows into a JSON encoded format

I am facing difficulties in converting a PHP array generated from an SQL query to a JSONObject using json_encode. I am utilizing Google Volley for connection. When dealing with a single row result, everything works fine, but when there are multiple rows, ...

Retrieve a document utilizing XHR on iOS Safari platform

I'm currently working on adding the capability to download a file stored on a server. To access the file, I need to include the Authorization header, requiring me to send an XHR request to retrieve the file from the server. Since the file content is s ...

leafletjs: render Points of Interest (POIs) using canvas technology

I am looking for a way to efficiently draw multiple geo points using Leaflet and HTML5 canvas. My data source is geoJSON, but according to the documentation of Leaflet, drawing geo positions as canvas is currently not supported. var anotherGeojsonLayer = ...

Tips for sending a file array together with other string/int variables from JavaScript to PHP

I am looking to pass the imageArray[] along with a variable trackNo. Passing the imageArray[] is not an issue, but I am unsure of how to include other variables with the FormData(). When researching online, I only came across examples of people passing a ...

Combine rows with the same value in the first column of an HTML table

My HTML table has dynamic content, and I need to merge rows in the first column only if their values are identical. You can see an image of the table here. Specifically, if the values in the first column match, those rows should be merged together while le ...

An error occurred as the Serverless Function timed out while attempting to load a dynamic route in Next.js version 13

I have a basic Next.js application with the following route structure: /contentA/ - Static - Initial load: 103 kB /contentA/[paramA]/groups - SSG - Initial load: 120 kB /contentB/[paramA]/[paramB]/[paramC] - SSR (client component) - Initial load: 103 kB ...

methods for including a sub-array into a main array within Swift

{ "firstName": "AA", "lastName": "BB, "shortName": "CC", "nric": "12/AAA(N)123456", "gender": "F", "dob": "1.1.2000", "password": "admin123", "photo": { "image": "hello", "thumb": "world" } } Is it possi ...