Mik_A Mik_A - 3 months ago 7
Javascript Question

avoid pushing duplicates to localStorage

I have a functioning code that adds the title of a class element to an array and then pushes it to a localStorage "database". Everything fine but i dont want to push elements there many times "if it is already there". Tried a couple of solutions but didnt quite get it. Any help is highly appreciated. Brain is melting..,

var stores=[]
jQuery('.additem').click(function() {
var x = jQuery(this).closest('h4.title').text();
if ((x == null) || (x == "") || (x == ($.inArray(this.x) > -1))) {
jQuery(this).closest('.infobox').html('Already there or empty.');
jQuery(this).closest('.infobox').show().delay(500).fadeOut(1000);
} else {
stores.push(x);
console.log(stores);
window.localStorage.setItem("database", stores.join(" + "));
}
});


Also tried with

(x == (stores.indexOf(this) > -1))


And a couple of something else.
Thanks

Answer

I think you are overdoing it. Doesn't this just work:

if ((x == null) || (x == "") || stores.indexOf(x) > -1) {
Comments