What is the best way to remove a particular element from an array stored in Local Storage?

Currently working on a web application that features a grade calculator allowing users to add and delete grades, all saved in local storage. However, encountering an issue where attempting to delete a specific grade ends up removing the most recently added grade instead. How can I accurately target and remove a particular integer from an array?

<template>
  <div>
    <h2>Grade Calculator</h2>
    <div>
      <ul>
        <li v-for="(grade, index) in grades" :key="index">
          {{index+1}}. Grade: {{grade}}
          <button v-on:click="deleteGrade(index)">Delete</button>
        </li>
      </ul>
      <div>
        <label>New Grade:</label>
        <input type="text" v-model="newGrade" />
        <button v-on:click="addGrade()">Add</button>
      </div>
      <br />
      <div>
        <p>Average: {{ calculateAverage() | round}}</p>
      </div>
    </div>
  </div>
</template>
<!-- The Script-->
<script>
export default {
  data() {
    return {
      grades: [],
      newGrade: null,
      average: 0,
      formattedNumber: ""
    };
  },
  name: "Home",
  
  methods: {
    deleteGrade(index) {
      this.grades.splice(index, 1);
      localStorage.removeItem("grades");
      localStorage.setItem("grades", JSON.stringify(this.grades));
    }
  },

  mounted() {
    this.grades = JSON.parse(localStorage.getItem("grades")) || [];
  },
};
</script>

Answer №1

To start the deletion process, you will first need to specify the specific grade you want to delete using the function delGrade(gradeToDelete). Once you have identified the grade to delete (and its corresponding index with

this.grades.indexOf(gradeToDelete)
), you can then proceed to work with that particular index.

Additionally, it is important to note that the .splice method requires a deleteCount parameter to remove the element at the specified index. Therefore, consider modifying this.grades.splice(idx); to this.grades.splice(idx, 1);

Answer №2

If your data is in the form of integers stored within an array, you can follow a similar approach to manage it like shown below.

const numbers = [4, 7, 2, 9, 1];
localStorage.setItem('numbers', JSON.stringify(numbers));

To eliminate a specific integer from the array, you would need to extract it back into an array structure and then utilize the Array.prototype.filter method to create a modified array without the intended number.

const numberToRemove = 2;
const storedNumbers = JSON.parse(localStorage.getItem('numbers'));
const updatedNumbers = storedNumbers.filter(num => num !== numberToRemove);
localStorage.setItem('numbers', JSON.stringify(updatedNumbers));

Answer №3

Remember to specify the ID you wish to remove from the array

 <button v-on:click="deleteItem(id)">Remove</button>

Once you have the ID, you can proceed with its deletion

    deleteItem: function(itemId) {
      this.items.splice(itemId, 1);
      localStorage.removeItem("items"); // not necessary as all items will be overwritten in the next line
      localStorage.setItem("items", this.items);
    }

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

Triggering multiple functions by clicking on the Icon

I'm trying to execute two different functions when the user clicks on the Icon, but I keep getting an error that says: Expected onClick listener to be a function, instead got a value of object type. Can someone please help me figure out what I am doin ...

Vuex is throwing a mysterious ReferenceError that is leaving developers

Currently, I am developing a Single Page Application (SPA) using Vue.js and Vuex. Within this project, I have set up some data in the store and displayed it in a child component. This child component includes radio buttons that trigger a function called ge ...

What is the best way to connect a line from the edge of the circle's outermost arc?

I am attempting to create a label line that extends from the outermost point of the circle, similar to what is shown in this image. var svg = d3.select("body") .append("svg") .append("g") svg.append("g") .attr("class", "slices"); svg.append("g") ...

Ways to interact with similar dynamic controls in Javascript

I have an aspx page with a Select box control: <select name="selViewPerPage" id="selViewPerPage" style="width:30px"> To ensure consistent styling across all browsers, I am replacing this html control with a dynamic select box using "selectBox.js". ...

MongoDB not being updated

Currently, I am a student delving into the world of full-stack JavaScript development. One resource that I have found particularly helpful is a LinkedIn course where the project involves creating a blog with an "upvoting" feature. However, I have encounter ...

Ways to trigger an event or invoke a function after initializing Stripe JS

My checkout page is optimized with the new Stripe Payment Element for fast loading using SSR. However, I am facing an issue where the element sometimes causes the page to reload 2 or more times before functioning properly. Occasionally, it also displays ...

Using Typescript to assign a new class instance to an object property

Recently, I crafted a Class that defines the properties of an element: export class ElementProperties { constructor( public value: string, public adminConsentRequired: boolean, public displayString?: string, public desc ...

"Vue i18n encountered an issue while attempting to retrieve translations from the locales

I have integrated i18n into my Vue project using the command vue add i18n However, after adding i18n, it seems unable to load from the json files located in the folder locales The issue specifically arises when trying to access the message key in the Hel ...

The standard TextField functionality was disrupted by the update to MUI v5

After typing a comment in the TextField and trying to click Done, nothing happens because the TextField still has focus. The first click removes the focus, while a second click is needed to complete the action. https://i.sstatic.net/XJvp0.png <TextF ...

Utilize Node.js to sort through data

One API is providing me with this type of response. I need to extract the latitude and longitude of a single entity. How can I filter this data using JavaScript (Node.js)? header { gtfs_realtime_version: "1.0" incrementality: FULL_DATASET timestamp: ...

How to locate the position of a specific word on a webpage using jQuery

In my div, I am struggling to search like an editor. Despite multiple attempts, I have not found a solution yet. Can someone please advise me on how to resolve this issue? <div id="content"> <p> Lorem Ipsum is simply dumm ...

Trouble with Ruby on Rails jQuery interactions when using the tokenInput gem

Currently, I am developing a rails app and attempting to incorporate this gem for a text field https://github.com/exAspArk/rails-jquery-tokeninput Despite having the gem correctly installed and included in my _form.html.erb file, I keep encountering the ...

Utilize environment variables to access system information when constructing an Angular 2 application

In order to build my Angular application, I want to utilize a single system variable. System Variable server_url = http://google.com This is how my Environment.ts file looks: export const environment = { production: false, serveUrl: 'http://so ...

How can I modify the card loading style in Vuetify?

My preference is for the <v-card :loading="loading">... However, I would like to modify the appearance from a linear progress bar to something like an overlay. I am aware that changing colors can be done by binding color instead of using boolean ...

Error in Vue: Expected object but received a function instead of a valid value

I am attempting to apply a computed function to my style. However, the computed function uses a property within it and Vue is throwing an error stating that it expects an object but is receiving a function. Below is the code in question. <template> ...

``Vuejs pagination does not work properly with bootstrap 4 due to compatibility

I am encountering difficulties with the VueJS pagination package found on Github. While it functions properly with Bootstrap 3, I am facing issues when using Bootstrap 4. The problem lies in Bootstrap 4 not styling the list items correctly. When I apply t ...

Encountering problems when attempting to effectively filter a list of products using data

<div id="prod"> <div class="content" data-brand="Andrew" data-price="1000" data-store="JCPenny">Andrew</div><br /> <div class="content" data-brand="Hill" d ...

To incorporate node_modules CSS into a Vue.js application that is utilizing SCSS, follow these steps

After deploying my application to AWS, I noticed that the application was rendering correctly except for the Syncfusion controls, which were not rendering correctly. Surprisingly, there were no errors shown in the Google Chrome console. On my local machine ...

Dealing with massive arrays in C++

I have recently taken over a Java codebase from a past student and am in the process of converting it to C++, a language I am more comfortable with. As I dig into the code, I'm on the lookout for areas where I can make improvements. The main issue at ...

React: automatically close other SubMenus when a new SubMenu is opened

Is there a way to automatically close all other open SubMenus when a user opens a new SubMenu? If anyone has a solution, I would greatly appreciate the help! This is my code: Menu.tsx -> const Menu: React.FC = ({ data }) => { return ( ...