0

I have an array stored in localStorage. How can I remove the value of an array and save it in localStorage again?

var cars = ["Saab", "Volvo", "BMW"];
localStorage.setItem("cars", JSON.stringify(cars));

let modifiedCars = JSON.parse(localStorage.getItem("cars")).splice(0, 1)

// How do I remove cars[0] from the array and store it back into localStorage?

2 Answers 2

1

localStorage is a simple string-based storage. In order to remove an item, you need to read it (like you did), remove it (like you did) and store it again:

localStorage.setItem('cars', JSON.stringify(modifiedCars));
Sign up to request clarification or add additional context in comments.

2 Comments

Ok but how do I set this localStorage to "cars"?
Sorry, I was too quick :)
0

I prefer to remove the element by using .filter();

var cars = ["Saab", "Volvo", "BMW"];
localStorage.setItem("cars", JSON.stringify(cars));

let modifiedCars = JSON.parse(localStorage.getItem("cars")).filter(el => el!= "Saab")

localStorage.setItem("cars", JSON.stringify(modifiedCars ));

5 Comments

Thanks for the suggestion, but every time I try to use filter, it gives me this TypeError: localStorage.getItem(...).filter is not a function
@hiphopfeels localStorage.getItem returns a string, filter is on array prototype; we'd used it on JSON.parse(localStorage.getItem("cars")) not the .get of localstorage
I'm sorry, I don't understand can you maybe explain differently?
@hiphopfeels "randomString".filter() throws error; but [].filter() works fine; and that JSON.parse() will return an return an array
Okay, this is exactly what I was looking for. My problem was that I didn't use JSON.parse(). Thanks a lot! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.