简体   繁体   中英

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

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

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

You could use a Set which can be converted to and from an array for storage.

var s = new Set();
s.add(value);
localStorage.setItem('mySet',Array.from(s).toString())

var s = new Set(JSON.parse(localStorage.getItem('mySet'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM