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

Is it possible to programmatically refresh an Angular controller?

Within my HTML page, I have implemented three tabs with each tab linked to a unique controller. The structure is as follows: MainHTML (app.pages.managing.html): <div id="DetailsViewContainer"> <div ng-if="selectedTab === 'tab1&a ...

Looking to create a format for displaying short comic strips in a grid pattern

I am struggling to create an image grid for my small comics. I want to have 2 columns and 3 rows, but all the divs end up in the same place. I tried using display: flex, but it didn't work as expected. Additionally, I want the grid to be responsive, b ...

Combinations of Typescript dependent unions

I'm struggling with calling the given union that wraps a function and its argument. Is there a way to call it without having to cast? type Wrapper = { fn: (a: string) => void arg: string } | { fn: (a: number) => void arg: number } let f ...

Retrieving and storing data using jQuery's AJAX caching feature

When utilizing jQuery's $.ajax() method to perform an XHR based HTTP GET request to obtain a partial of HTML from a Ruby on Rails website, I encounter an issue. Specifically, every time a user clicks on tabbed navigation, I refresh an HTML table with ...

Looking for assistance in implementing specific styling techniques with React

Trying to implement a slider on my React page sourced from a Github repository. The challenge lies in adding the CSS as it is in JS format. Even after incorporating webpack and an npm compiler, the styling seems unrecognized. Any suggestions or solutions ...

Show or hide a component based on a mouse click in Vue JS

After a prolonged absence from working with Vue JS, I find myself in the process of displaying a list of data with a button for each item. The goal is to conditionally render a component when a button is clicked. I am wondering if there is a recommended a ...

Error: Unable to locate specified column in Angular Material table

I don't understand why I am encountering this error in my code: ERROR Error: Could not find column with id "continent". I thought I had added the display column part correctly, so I'm unsure why this error is happening. <div class="exa ...

One of my AngularJS directives seems to be malfunctioning while the rest are working fine. Can you help me troubleshoot

Recently, I've been immersing myself in the job search process and decided to create a website as a sort of online resume while also learning AngularJS. I enrolled in the Angular course on CodeSchool and am slowly building my website to my liking. (Pl ...

Manipulating the DOM results in the SWF being reloaded

Currently, I am utilizing jQuery to insert an SWF into the DOM. However, when the SWF loads and I attempt to clone or wrap it, the SWF ends up reloading. Preventing this reload is crucial for me. Here's an example: $('#test9').before(&apo ...

Adjust the content size to 100% based on the quantity of items in a row

I've been having a hard time creating an image gallery that adjusts its size automatically (width: 100%) based on the number of items it contains. For example, take a look at this gallery: http://codepen.io/anon/pen/eNMOEz .item { width: 75px; h ...

Tips for locating an element beyond the page source with Puppeteer

My goal is to extract specific information from a webpage by utilizing this code snippet to target an element and retrieve certain values within it: const puppeteer = require('puppeteer'); function run (numberOfPages) { return new Promise(a ...

Prevent repeating the same table header multiple times when generated dynamically with jQuery

I have an array called groups which contains name and regid. I want to display the name key as the column header of a table. To achieve this, I implemented the following code: var Name = v.name; var regId = v.regid; var rowStr = '<th d ...

I encountered a data discrepancy while attempting to link up with a weather API

This is my debut app venture utilizing node.js and express for the first time. The concept behind this basic application involves connecting to an external API to retrieve temperature data, while also allowing users to input their zip code and feelings whi ...

"Real-time image upload progress bar feature using JavaScript, eliminating the need for

I have successfully implemented a JavaScript function that displays picture previews and uploads them automatically on the onchange event. Now, I am looking to add a progress bar to show the upload status. However, all the solutions I found online are rel ...

Add the onclick() functionality to a personalized Angular 4 directive

I'm facing an issue with accessing the style of a button in my directive. I want to add a margin-left property to the button using an onclick() function in the directive. However, it doesn't seem to be working. Strangely, setting the CSS from the ...

Leveraging Amplify for offline storage while transitioning between HTTP and HTTPS protocols

Recently, I encountered an issue with Amplify 1.0a1 on my website. It seems that when storing the value of prod_id in localStorage on a page using HTTP, and then navigating to a page using HTTPS (such as the 'list' page), I am unable to access th ...

What is the process for developing an Alphabetizer Program?

I have been working on this and I am having trouble getting the "alphabetized" version to display. I've tried a few things already, but I'm not sure what is missing or needs to be changed. Any advice on how to fix this would be greatly appreciate ...

Using Vuex: Implementing methods to modify component data or invoke component functions directly from the Store

If I were to operate a store: import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) export default new Vuex.Store({ state: { foo: bar }, mutations: { updateComponent (state) { // calculation and reasoning ...

An error occurs in TypeScript when attempting to reduce a loop on an array

My array consists of objects structured like this type AnyType = { name: 'A' | 'B' | 'C'; isAny:boolean; }; const myArray :AnyType[] =[ {name:'A',isAny:true}, {name:'B',isAny:false}, ] I am trying ...

Ways to examine attributes assigned in the controller.$onInit function in AngularJS

In a certain scenario, I am initializing some variables in the controller's $onInit method. How can I verify that these properties are being set correctly? Controller ctrl.$onInit = function () { ctrl.devices = _.cloneDeep(ctrl.formDevices); }; ...