removing duplicate items from an array in Vue.js

I created a Pokemon App where users can add Pokemon to their 'pokedex'. The app takes a pokemon object from this.$store.state.pokemon and adds it to this.$store.state.pokedex. However, users can add the same pokemon multiple times to the pokedex, causing issues when trying to delete objects using .splice(index, 1). Currently, this method deletes the last item in the array, not the intended item. Is there a way to pass the key of the object to splice?

//Pokedex.vue
<template>
    <pokedex-card 
        v-for="(pokemon, i) in pokedex" 
        :key="`${i}+${pokemon.id}`"
        :pokemon="pokemon">
          <button @click="releasePokemon(i)">Release {{ pokemon.name }} ?</button>
    </pokedex-card>
</template>

methods:{
    releasePokemon(id){
      this.$store.dispatch('releasePokemon', id)
    }

And the vuex store:

//index.js
REMOVE_FROM_POKEDEX(state, id){
      //find pokemon position in array by matching it's object ID
      var pokePosition = state.pokedex.map(pokemon => { return pokemon.id }).indexOf(id)
      state.pokedex.splice(pokePosition, 1);
    }

Answer №1

If you're encountering a similar issue, I discovered that I needed to generate a new object while adding the pokemon item to the pokedex array. This allowed me to assign a unique reference number to it:

state.pokedex.push( { ref: pokemon.id + state.pokedex.length, poke: pokemon } );

Then, in the component where I displayed the pokemon from state.pokedex, I utilized the ref as the key:

<pokedex-card 
        v-for="pokemon in pokedex" 
        :key="pokemon.ref"
        :pokemon="pokemon">
</pokedex-card>

This way, in the store, I could remove the object easily:

REMOVE_FROM_POKEDEX(state, id){
   let index = state.pokedex.findIndex(pokemon => pokemon.ref === id);
   state.pokedex.splice(index, 1);
}

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

issues with the redirection functionality in the Play framework

I am currently working on an application that extracts data from Twitter profiles. I want to give the user the ability to select which parts of their profile should be used (for example, excluding tweets). To accomplish this, I plan to incorporate checkb ...

Recording a specialized event sent from a web component to React

Trying to incorporate a Lit web component into a React application has presented some challenges for me. This web component is expected to dispatch a custom event at some point, and I need to handle it in the React application appropriately. Despite my li ...

What is the best way to reload scripts each time a component is mounted?

My jQuery scripts include animation effects that need to be refreshed whenever something new is rendered on the page. However, I am facing an issue where the jQuery scripts are not being refreshed as needed. Below is my router configuration: export defau ...

Tips for concealing a collapsible navbar menu upon clicking elsewhere (Bootstrap 5)

I am trying to create a collapsible navbar menu: <div class="collapse navbar-collapse" id="navbarCollapsible"> .. menu items .. </div> My goal is to hide the menu whenever a user clicks outside of it (not just when click ...

Utilizing asynchronous programming for scenarios where two requests need to be sent, with the response from the first request being required for the second request

I have an async function that looks like this: exports.myFunction = async (req, res, next) => { if (some condition) { next() } try { const results = await axios.get(`https://a-domain.com/url/path`); const info = results.data; c ...

Call order for importing and exporting in NodeJS

This question is related to "code theory." Let's explore a scenario where I am utilizing the global namespace in a package. The structure includes a main entrypoint file, classes that are exported, and utility files used by the classes. Here's a ...

What is the best way to utilize AJAX in sending chosen files to a PHP script?

I currently have two forms set up. Form A includes fields for name, age, address, email, and a hidden text field that holds the names of images to be uploaded in form B. Form B allows users to browse and select their photos using an input type File. ...

Exploring the world of HighCharts

I am trying to use Highcharts to calculate and visualize the magnitude of a complex number. Currently, my code is displaying the real and imaginary values separately on the graph. However, I seem to be facing issues with the "For loop" that I implemented ...

Issue with querying and ordering products in Django using Python when passing values through the GET request

I have been working on a project where I need to filter products and sort them by price in ascending and descending order. Here is the code snippet from my view: def is_valid_queryparam(param): return param != '' and param is not None def f ...

Transform one column into several columns

I am working with a function that populates a table row by row. Here is the code: function renderListSelecoes(data) { // JAX-RS serializes an empty list as null, and a 'collection of one' as an object (not an 'array of one') va ...

Looking for help in resolving console error displaying 'Uncaught (in promise)' notification

I've encountered an issue while trying to troubleshoot a problem that involves using the find() method, which is causing an error. import { CART_ADD_ITEM, CART_REMOVE_ITEM } from '../constants/cartConstant'; const cartReducers = (state = { ...

The UseEffect function is displaying an inappropriate value, however, it only occurs once

My goal is to display the state value whenever the password is changed using the useEffect hook in React. It's working fine for the password, but the issue arises when I try to change the email. The console also renders the email value, which is not i ...

What is the best way to trim a string property of an object within an array?

I am seeking a solution to access the "description" property of objects within an array and utilize a string cutting method, such as slice, in order to return an array of modified objects. I have attempted using for loops but have been unsuccessful. Here ...

What is the purpose of passing data into the 'success' function of an AJAX request?

Recently, I embarked on a journey to learn jQuery and AJAX, but I found myself tangled in confusion when it came to AJAX requests. To gain practice, I decided to create a simple TodoApp using Node, jQuery, and Bootstrap. While I managed to grasp GET and P ...

Building Individual Elements in Angular 2

My task involves creating two distinct components in Angular 2, the Users component and the Clients component. These components are not nested and do not have any relationship. To call these components separately, I typically use main.ts as the main entry ...

Firebase version 9 - Retrieve the content of a referenced document

I'm having trouble locating the documentation I need. Within my Firebase Firestore project, there is a collection called users. Within users, there are three collections: companies, policies, and stores. In the policies collection, I have fields for ...

JavaScript: Share module contents internally through exporting

When working with Java, there are 4 different visibility levels to consider. In addition to the commonly known public and private levels, there is also the protected level and what is referred to as the "default" or "package-local" level. Modifier Clas ...

Can jQuery help me identify which <input type='image> was clicked within a form containing several submit images?

Consider this hypothetical scenario: <form> <input type="text" name="some_name" value="val" id="some_name"> <input type="image" value="action" alt="Add To Cart" name="add" src="/images/submit.gif"> <input type="image" value="act ...

jQuery selector unable to locate the specified class in the table row

After receiving an array of strings as a response from an SQL query, I am using JavaScript to dynamically add this data as rows to an HTML table: loadUsers: function() { . . . function displayUsersOnTable(response) { for(var i = ...

JavaScript Application - Problem with Universal Windows Script

I recently built a website utilizing material design lite for the aesthetics: Here are the scripts included: <script src="./mdl/material.min.js"></script> <script src="Scripts/angular.min.js"></script> The necessary .css fi ...