Mik_A Mik_A - 1 year ago 93
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.');
} else {
window.localStorage.setItem("database", stores.join(" + "));

Also tried with

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

And a couple of something else.

Answer Source

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

if ((x == null) || (x == "") || stores.indexOf(x) > -1) {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download