Search code examples
javascripthtmllocal-storageignore-duplicates

HTML5 LocalStorage - check for duplicate values


I'm saving a list of images (from a gallery) to a device using LocalStorage. I've solved the problem for the most part - getting data in and out, and populating an HTML list of items that are in there. Easy.

I'm now trying to put a check in to look at the item being saved, check all the values in the database, and only add it if it isn't a duplicate. As I'm building this I'm getting deeper and deeper in a hole and am at the point where I need a bit of help.

Here's my function at the moment:

function storeFavourite(currentImage) {
for (var i=0; i < localStorage.length; i++) {
    item = localStorage.getItem('fav'+i);
    if (item = currentImage) {
        console.log('fav'+i+', '+currentImage+' in db already');
    } else {
        next = localStorage.length;
        localStorage.setItem('fav'+next, currentImage);
        console.log('fav'+next+', '+currentImage);
        updateFavouritesList(); 
    }
}
}

It's a big mess and I've completely confused myself. Can anyone help me figure it out?

I'm not at all opposed to reformatting the data structure if needed. At the moment the keys are fav0, fav1 and so on.

The updateFavouritesList() function used there just iterates over the localStorage database and creates <li> items from it to add to a list.


Solution

  • You have an error in the line:

    if (item = currentImage) {
    

    You're assigning item. If item isn't null/empty/zero/falsy, then it will always resolve as true. Perhaps it should be:

    if (item == currentImage) {
    

    or even:

    if (item === currentImage) {
    

    depending on which type currentImage is.

    EDIT: In any case, here is a function which will do what you're looking for:

    function storeFavourite(item) {
        for (var i in localStorage) {
            if (localStorage[i] === item) return;
        }
        localStorage["fav" + localStorage.length] = item;
    }