How to Remove or avoid duplicate values in LocalStorage - javascript

When user click on button it will store some value in LocalStorage and if user click same button again it will store same value again in LocalStorage, How can i remove or avoid duplicates same values in LocalStorage ?!
Can anyone please help me :)
HTML:
<a onclick="AddToCart('ae90ac1a-64c4-49a7-b588-ae6b69a37d47');">Add to Cart</a>
<a onclick="AddToCart('3e58aa74-4585-4bee-b2e0-ed39a1d95442');">Add to Cart</a>
JavaScript:
function AddToCart(varer) {
var itemsLocalStorage = JSON.parse(localStorage.getItem("itemsline") || "[]");
itemsLocalStorage.push(varer);
localStorage.setItem("itemsline", JSON.stringify(itemsLocalStorage));
}
LocalStorage (Before user click) :
[]
LocalStorage (When user click ):
["ae90ac1a-64c4-49a7-b588-ae6b69a37d47"]
LocalStorage (When user click again):
["ae90ac1a-64c4-49a7-b588-ae6b69a37d47","ae90ac1a-64c4-49a7-b588-ae6b69a37d47"]
I tried with filter but for some reason it's not going to work:
itemsLocalStorage = itemsLocalStorage.filter(e => e === varer);

Grab the array from localStorage, push the value to the array if it's not found in that array already, and then update localStorage if we pushed.
var array = JSON.parse(window.localStorage.getItem("itemsline")) || [];//the "|| []" replaces possible null from localStorage with empty array
var value = "some value";
if(array.indexOf(value) == -1){
array.push(value);
window.localStorage.setItem("itemsline", JSON.stringify(array));
}
Here's a version of this same code that is more explanatory of how it works:
//All values stored in localStorage are strings.
//Grab our itemsline string from localStorage.
var stringFromLocalStorage = window.localStorage.getItem("itemsline");
//Then parse that string into an actual value.
var parsedValueFromString = JSON.parse(stringFromLocalStorage);
//If that value is null (meaning that we've never saved anything to that spot in localStorage before), use an empty array as our array. Otherwise, just stick with the value we've just parsed out.
var array = parsedValueFromString || [];
//Here's the value we want to add
var value = "some value";
//If our parsed/empty array doesn't already have this value in it...
if(array.indexOf(value) == -1){
//add the value to the array
array.push(value);
//turn the array WITH THE NEW VALUE IN IT into a string to prepare it to be stored in localStorage
var stringRepresentingArray = JSON.stringify(array);
//and store it in localStorage as "itemsline"
window.localStorage.setItem("itemsline", stringRepresentingArray);
}

Take temp array and then check for duplicate values.
var arr = ["ae90ac1a-64c4-49a7-b588-ae6b69a37d47","ae90ac1a-64c4-49a7-b588-ae6b69a37d47"]
function squash(arr){
var tmp = [];
for(var i = 0; i < arr.length; i++){
if(tmp.indexOf(arr[i]) == -1){
tmp.push(arr[i]);
}
}
return tmp;
}
console.log(squash(arr));

You could use filter
array.filter((item, index) => array.indexOf(item) === index)
const array = ["ae90ac1a-64c4-49a7-b588-ae6b69a37d47","ae90ac1a-64c4-49a7-b588-ae6b69a37d47"];
const filteredArray = array.filter((item, index) => array.indexOf(item) === index);
console.log(filteredArray)

You can use Set object of js it always add value only when it is unique
var array = JSON.parse(localStorage.getItem("items")) || [];
let set =new Set(array)
set.add(newValue)
const toArr=Array.from(set)
localStorage.setImem("items",JSON.stringify(toArr))

Related

Delete specific string from Local Storage array

I have this code
function deleteElement() {
const myArray = map(listItems, getText);
var elementToDelete =document.getElementById('deleteElement').value;
const index = myArray.findIndex((item) => item.includes(elementToDelete));
if (index > -1) {
// delete and update local storage
console.log("found element and index ", index);
let moment = localStorage.getItem('pelis_guardades');
let deleted = moment.splice(index, 1);
localStorage.setItem('pelis_guardades', JSON.stringify(deleted))
console.log(deleted);
}
}
I have found the index of the element of the array that I want to delete, everything's good, but now I would like to "update" the local storage to delete the item from the index.
I can delete the specific value on the array that loads into the local Storage. Called myArray.
const myArray = map(listItems, getText);
myArray contains the "raw string data" that then gets put on the local Storage via,
localStorage.setItem('things',JSON.stringify(myArray));
How can I delete from the localStorage?
I've tried, the splice method on the local storage but doesn't work!!
Thanks!
try to parsing the moment variable to JSON
using
edit
function deleteElement() {
const myArray = map(listItems, getText);
var elementToDelete =document.getElementById('deleteElement').value;
const index = myArray.findIndex((item) => item.includes(elementToDelete));
if (index > -1) {
// delete and update local storage
console.log("found element and index ", index);
let moment = localStorage.getItem('pelis_guardades');
//try to add this code
let moment_parse = JSON.parse(moment);
let deleted = moment_parse.splice(index, 1);//edit
localStorage.setItem('pelis_guardades', JSON.stringify(deleted))
console.log(deleted);
}
before you splice the moment variable
The problem is that you've made a mistake using Array.splice.
This method mutates the given array.
You don't need the result of the splice operation. Instead you must pass the array as the new value to update the localstorage.
// 1. read value
const moment = JSON.parse(localStorage.getItem('pelis_guardades'))
// 2. mutate given array by removing one element from index.
moment.splice(index, 1);
// 3. write value
localStorage.setItem('pelis_guardades', JSON.stringify(moment))

Searching For Existing Values in Array

I have been trying to search for an existing value in an array like below
var values = []
values.push(localStorage.getItem('items'));
console.log(values);
if (values.includes(2)) {
alert('Already Exists.');
}
When i console the array values i have output as ["1,2,3,4,5,6"] so the code treats the array as having just one index which is index[0] which makes the search quite challenging for me.
My challenge is how to find the value 2 in the array values ?
localStorage can only hold strings. As such you need to convert the value you retrieve in to an array, which can be done using split().
Also note that the resulting array will contain string values, so you need to use includes('2'). Try this:
var values = "1,2,3".split(','); // just for this demo
//var values = localStorage.getItem('items').split(',');
console.log(values);
if (values.includes("2")) {
console.log('Already Exists.');
}
Hope this help you.
var names_arr = '["1,2,3,4,5,6"]';
names_arr = names_arr.replace("'",'');
function checkValue(value,arr){
var status = 'Not exist';
for(var i=0; i<arr.length; i++){
var name = arr[i];
if(name == value){
status = 'Exist';
break;
}
}
return status;
}
console.log('status : ' + checkValue('3', names_arr) );
console.log('status : ' + checkValue('10', names_arr) );
First of all, this isn't jQuery, it's vanilla JS.
Second, after doing localStorage.setItem("items", [1,2,3,4,5,6]);, items in local storage will equal to "1,2,3,4,5,6", which is no longer the appropriate format.
Rather, save your array with localStorage.setItem("items", JSON.stringify([1,2,3,4,5,6]));. When you want to retrieve those items, write let vals = JSON.parse(localStorage.getItem("items"));, and search in vals with
vals.includes(2) for a true/false answer,
vals.find(val => val === 2) for 2 or undefined,
val.indexOf(2) to get the index of the
first element equal to 2.
Hope this helps.
firstly get the values from local storage store it in a variable, split it using the split
function, then check if the number is inside the array, alert the message if it returns true
var values =localStorage.getItem('items')
var spliter = values.split(',')
console.log(spliter);
if (spliter.includes('2') == true) {
alert('Already Exists.');
}

How to delete a specific string entry out of array

I am trying to delete string out of array but the string is staying there. Any suggestions?
$scope.removeFavorites = function (word) {
debugger;
// retrieve it (Or create a blank array if there isn't any info saved yet),
var favorites = JSON.parse(localStorage.getItem('favoritesInfo')) || [];
for (var i = favorites.length - 1; i >= 0; i--) {
if (favorites[i] === word {
favorites.splice(i, 1);
console.log(favorites[i]);
}
}
//favorites.pop();
// localStorage.setItem('favoritesInfo', JSON.stringify(favorites));
console.log(localStorage.getItem('favoritesInfo'));
}
In the above code the splicing is being done to favorites array which gets the values from the localstorage
var favorites = JSON.parse(localStorage.getItem('favoritesInfo')) || [];
so the value is removed in favorites array but not in the localstorage.
localStorage.getItem('favoritesInfo') still contains the complete set of values.
You have two solutions.
Use the favorites array which is your filtered set of list where
ever needed.
Update the local storage with the favorites array to
keep both in sync.

FInd object in array by value and update entire object

I have a list of objects and sometimes I receive an update from the API for one of those objects and what I need to do is to find the object with the id of the one to update and update the entire object...
I was trying to avoid a for loop because the list could be very very long.
So what I was trying to use is $.grep but it doesn't seem to work as expected.
Here is what I tried so far:
// item is the response data from the API
var item = res.item;
var index = $.grep(arrayOfItems, function (e, i) {
if (e.id === item.id) {
return i;
}
});
arrayOfItems[index] = item;
the item is not updated unfortunately...
If it's speed you're after, especially with a long list, you may consider indexing your list by id when you first retrieve it, making updates later quicker than having to loop the entire array to find an index.
To demonstrate, assume you have retrieved an array of objects
var data = [
{id:1,data:'hello'},
{id:2,data:'world'},
{id:3,data:'foo'},
{id:4,data:'bar'}];
now create an object which represents your data where the property is the Id (object properties cannot start with a number, so if id is numeric, prefix it) and the value is the index back into the original array. So, the above data would be transformed to
var dataIndex = {
id1:0,
id2:1,
id3:2,
id4:3
};
This can be done trivially with a function
function indexDataById(data)
{
var index = {};
$.each(data, function(e,i){
index['id' + e.id] = i;
});
return index;
}
var dataIndex = indexDataById(data);
Now, when it comes to your update, you can find the index instantly using the id
var updateId = 2;
var elementIdx = dataIndex ['id' + updateId];
data[elementIdx] = myNewData;
The one complication is that you need to go back and update the index if the id of the new data has changed:
var updateId = 2;
var elementIdx = dataIndex [`id` + updateId];
data[elementIdx] = myNewData;
delete dataIndex[elementIdx]
dataIndex['id' + myNewData.id] = elementIdx;
This should be easy enough to handle atomically with your update.
$.map and $.grep return both an array so you will never get the index.
Inside $.map or $.grep function you need to return true or false based
on your filter logic. They re not useful in your case.
if your structure is not ordered you can only loop trough it and stop the loop when you find your element... like that:
var item = res.item;
var index = "";
$.each(arrayOfItems, function(i,v){
if(item.id == v.id){
index = i;
return true;
}
});
arrayOfItems[index] = item;
if you wanna order your structure before loop use this:
arrayOfItems.sort(function(a, b) {
return a.id > b.id;
});
i ve made a fiddle with an example https://jsfiddle.net/L08rk0u3/
try this way using $.grep
var arrList = [
{name :11,id :11},{name :12,id :12},{name :111,id :111},
{name :13,id :13},{name :15,id :15},{name :11,id :11},
{name :41,id :41},{name :31,id :31},{name :81,id :81},
{name :91,id :91},{name :13,id :13},{name :17,id :17},
{name :1111,id :1111}
]
console.log(arrList);
var respItem ={name :1111000,id:1111};
var intSearchedIndex;
$.grep(arrList,function(oneItem,index){
if(respItem.id==oneItem.id){
return intSearchedIndex = index;
}
})
arrList[intSearchedIndex] =respItem;
console.log(intSearchedIndex,arrList);
Try with map method like this.
Code snippets:
// item is the response data from the API
var item = res.item;
var index = $.map(arrayOfItems, function (e, i) {
if (e.id === item.id) {
return i;
}
});
if(index.length)
arrayOfItems[index[0]] = item;
Update:
arrayOfItems[index] = item;
This will work if index array has an single element. See fiddle
But,
arrayOfItems[index[0]] = item;
This is the appropriate way since it is an array.

How to stock array with localStorage (Chrome Extension)?

I tried to stock an array in localStorage but then I read it was impossible. So I tried that:
array = {};
array.name = $('[name="name"]').val();
array.username = $('[name="username"]').val();
array.password = $('[name="password"]').val();
alert(localStorage['accounts']);
local = JSON.parse(localStorage['accounts']);
localu = local.push(array);
alert(JSON.stringify(localu));
In fact the scripts stops at the first alert which returns '[]' (I previously put that value to check the result).
Why isn't my script working?
JavaScript, {} is an Object. [] is an Array.
var array = [] and var array = new Array() do the same thing.
An array is an ordered container of stuff, each value has an index not a key.
An object is a named container of stuff, each "stuff" has a key.
Your array is definitely an object.
var data = {};
data.name = $('[name="name"]').val();
data.username = $('[name="username"]').val();
data.password = $('[name="password"]').val();
alert(localStorage['accounts']);
// > undefined OR the value
local = JSON.parse(localStorage['accounts']);
// local contains a parsed version of localStorage['accounts']
localu = local.push(array);
// localu = 0 (push returns the length i think?)
alert(JSON.stringify(localu));
Try the following. I've not tested it, but might work.
var data = {};
data.name = $('[name="name"]').val();
data.username = $('[name="username"]').val();
data.password = $('[name="password"]').val();
if (localStorage['accounts'] == undefined) { // fixed
// does the key exist? No so create something to get us started
localu = { accounts: [] };
} else {
// the key exists! lets parse it
localu = JSON.parse(localStorage['accounts']);
}
// add the new "data" to the list
localu.accounts.push(data);
// save the results (we have to stringify it)
localStorage['accounts'] = JSON.stringify(localu);

Categories

Resources