Enhance the JavaScript Array and reformat it once more

Alright, so here's the scenario:

var inventory = ["axe", "shield", "bow", "staff"];

I decided to convert this array into a string and store it in my localStorage.

localStorage.setItem("inventory", JSON.stringify(inventory));

Then I implemented a function that updates the value at a specific index of an element in the passed variable with an empty string. I did this so I could have a way to verify if a particular item was previously stored at a certain index. The value is removed but the index remains for future reference.

function updateInventory(item) {
    var updatedItems = JSON.parse(localStorage.getItem("inventory"));   //fetching original array
    var idx = updatedItems.indexOf(item);
    if (idx > -1) {
        updatedItems[idx] = "";  //updating new array
        localStorage.setItem("inventory", JSON.stringify(updatedItems)); //changes not saved
    }
}

Unfortunately, the modified array doesn't get stored back into localStorage as expected.

Answer №1

Everything is working perfectly for me: http://jsfiddle.net/tto685z4/

var items = ["shovel", "sword", "rope", "gun"];

localStorage.setItem("items", JSON.stringify(items));

function removeItem(itm) {
    var itemArray = JSON.parse(localStorage.getItem("items"));   //original array
    var index = itemArray.indexOf(itm);
    if (index > -1) {
        itemArray[index]="";  //modified new array
        localStorage.setItem("items", JSON.stringify(itemArray)); //not storing
    }
}

removeItem('rope');

alert(localStorage.getItem('items'));

Returns ["shovel", "sword", "", "gun"]

You may have attempted to remove an item that does not exist.

Answer №2

To completely remove an element, simply follow these steps:

itemArray[index]="";

replace with:

itemArray = itemArray.splice(index, 1) and voilà! The element will be gone forever

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

Steps for setting up i18nextStart by including the i

I am working on developing a multilingual app using the i18next package. Unfortunately, I am experiencing issues with the functionality of the package. Below is an example of the i18next file I have been using: import i18n from "i18next"; impor ...

Passing an array from PHP to JavaScript without using JSON

I'm currently working on a project for school and I've hit a roadblock. My task involves accessing a database, converting the rows into an array, and then passing it to a JavaScript file to generate a graphic using the Google Charts API. Unfortu ...

What is the correct method for iterating through this array of objects and eliminating those with either null or empty item.text values?

Currently, I am working with the following Array: const contactInfo = computed(() => { return [ { id: 'address', icon: 'detail/clubLocation', text: `${props.data.contactInfo.address}` ...

Should I consolidate my ajax requests into groups, or should I send each request individually?

Currently working on an ajax project and feeling a bit confused. I have 3 functions that send data to the server, each with its own specific job. Wondering if it's more efficient to group all the ajax requests from these functions into one big reques ...

Guide on securely presenting an HTTP-only cookie as a bearer token, without the use of Angular.JS

Can a JWT be securely stored as an HTTP-only cookie and also used as a bearer token without relying on Angular.JS? I believe this could be achievable, as Angular.JS offers similar features (although I'm not sure if they use an HTTP-only cookie to sto ...

Access a website from a different domain and include JavaScript code dynamically

My goal is to develop a mobile-friendly web app that loads a website from a different domain and applies JavaScript code to adjust the layout. I have heard that JavaScript typically does not allow cross-domain requests, so I'm wondering how this could ...

Can you modify a attribute value in one HTML file from another?

I currently have a website and I am looking to modify the aria-expanded value of an expandable paragraph on another page when I click on an anchor element in the main page. What changes do I need to make in my main.html file in order to update the aria-exp ...

CSS Element Overlapping Issue in Safari Browser

I am currently developing an audio player for my application that includes a pause/play button, next button, and back button. I have encountered a problem specifically on Safari where the back/pause buttons are overlapping each other. The play/pause button ...

Issue with Bootstrap 4 nested tabs retaining active status

I'm having some issues with my nested tabs, both vertical and horizontal, as they are not switching the active states properly and some bugs are arising. body { min-height: 100%; } <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/b ...

Guide on redirecting the original URL when a partial URL or short URL is entered

Is it possible in PHP to automatically redirect a URL if a partial match like the ones managed by Stack Overflow or other similar sites is detected? For example, can a URL like https://stackoverflow.com/questions/21150608/htaccess-redirect-partial be auto ...

How can the reference to a promise be used in Node.js UnhandledRejection event parameters?

When an error occurs, we have options for handling it such as recording it in logs, displaying it on the page or console, and more. But what about the promise reference passed to the handler as the second parameter? process.on('unhandledRejection&apos ...

Experimenting with applying jquery .slideDown() to multiple classes in order to create dynamic animations

I am facing an issue while using .slideDown() with multiple classes. I want only one class to toggle/dropdown at a time, but currently when I press the button, all classes show up instead of just the one I want to display. How can I achieve this? Here is ...

Create a unique custom spinning loader for a straightforward Vue.js application

I've set up a basic Vue project on codesandbox.io that includes vue-router and a custom spinner for loading. Spinner.vue: <template> <div class="spinner" v-show="loading"> <span class="sync" v-bind:style="[spinnerStyle, spinnerD ...

Organize various base arrangements within Angular version 2

One thing I can accomplish in my angularjs application using ui.router is: $stateProvider .state('app', { url: '', abstract: true, template: '<div data-ui-view></div>' ...

Handle errors originating from unsuccessful connections to a server named "Event" when using RxJS's fromEvent method

Using rxjs fromEvent to establish a connection with a named sse Event, I am looking to handle an Error in case of connection loss namedEvent() { try { const eventSource = new EventSource( 'adress' ); return fromEvent ...

Showing the user's current location on a MapView in React Native

I'm having trouble setting the initial location of a MapView in my React Native app to the device's geolocation. Currently, I'm using a ref to update the coordinates with the help of the geolocation package. However, I'm facing an issu ...

What is the process for attaching text or labels to an object, similar to applying decals?

Check out this website: On this site, you can create text, add it to objects like a decal, and then click "Ok" to confirm. Is there a way to make this effect visible on the design? Many thanks in advance! ...

Two conflicting jQuery plugins are causing issues

In my journey to learn jQuery, I encountered an issue while working on a website that utilizes a scroll function for navigating between pages. The scripts used in this functionality are as follows: <script type="text/javascript" src="js/jquery-1.3.1.mi ...

Obtain data from a popup window and transfer it back to the main parent window

I am having trouble with a pop-up window that contains selections. After the user chooses options, I want those selected options to appear in the main window without refreshing it. I am utilizing JavaScript for this task, but I am struggling to find a way ...

VueJS component experiencing stagnant DOM updates

I have reviewed similar posts on "DOM not updating", but have yet to find a solution. I am working on a task app and it can successfully load, add, and delete tasks from Firestore. However, I'm facing two issues and would like to address the first one ...