Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

137
Views
How to avoid getting duplicated elements on localstorage array

i have the following code that generates a new element on an array in my localstorage each time i click on a button

let addCartItemButtons = document.getElementsByClassName('product-description-add')
for (let i = 0; i < addCartItemButtons.length; i++){
    let button = addCartItemButtons[i]
    button.addEventListener('click', function(event){
        let buttonClicked = event.target
        let getTitle = buttonClicked.parentElement.parentElement.parentElement.querySelector('.product-title').innerText
        let getImage = buttonClicked.parentElement.parentElement.parentElement.querySelector('.product-header img').src
        let getColor = buttonClicked.parentElement.parentElement.querySelector('.product-description-text li span').innerText
        let getSize = buttonClicked.parentElement.parentElement.querySelector('.product-description-text li select').value
        let getPrice = buttonClicked.parentElement.parentElement.querySelector('.product-description-price').innerText
        let getSpan = buttonClicked.parentElement.parentElement.querySelector('li span').getAttribute('id')
        let oldItems = JSON.parse(localStorage.getItem('newProduct')) || [];
        let newItem = {
            'id': i+1,
            'title': getTitle,
            'image': getImage,
            'color': getColor,
            'size': getSize,
            'price': getPrice,
            'spanid': getSpan,
        };
        let data = JSON.parse(localStorage.getItem('newProduct'))
        if(localStorage.getItem('newProduct') == null) {
            oldItems.push(newItem);
            localStorage.setItem('newProduct', JSON.stringify(oldItems));
        } else {
            if(data.indexOf(newItem) == -1){
                oldItems.push(newItem);
                localStorage.setItem('newProduct', JSON.stringify(oldItems));
            }else{
                alert('element already added')
            }
        }
    })
} 

My problem is that I've tried to create a validation to check if the element has already been added to the local storage, so in that case there should appear the alert, but it's not working at all and I'm still being able to add an element to my localstorage after I added it for the first time. I can't get of how to resolve this, any ideas? :)

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Problems are arising because objects do not compare as equal just because they have the same property values.

let oldItems = JSON.parse(localStorage.getItem('newProduct')) || [];

creates oldItems as an empty array or an Array of newly created objects with property values representing previous items clicked and saved.

let data = JSON.parse(localStorage.getItem('newProduct'))

will also create an array of new objects for previous buttons clicked, if there were any, but won't contain the same objects as oldItems because JSON.parse creates new objects each time it is called.

Defining newItem also creates a new object which will not be the same object as any of the entries in oldItems or data.

To solve the problem you could add unique product codes to all items, so you can search previous data for a match based on product code alone, or write a comparison routine to check all the properties that need differentiating (such as color).

Personally I would try to get a product-id added into page data, search for it among previous items, and if product-ids match, then then the item has been been clicked before (but the customer could be ordering a different color).

Be wary of using the button loop counter as an id value, or even the image source string - it's easy to imagine ways they could go wrong or be compromised by page changes outside your control.

about 4 years ago · Juan Pablo Isaza Report

0

So thanks for the help I've received from @traktor, I was able to come up with a solution to this problem. I've added a data-prodid to each product and then pass it as 'id' to localstorage. Then I check if there's any element in my array that contains the same ID i'm clicking into and if there's any result, then an alert gets executed. Otherwise, the element gets saved.

let addCartItemButtons = document.getElementsByClassName('product-description-add')
for (let i = 0; i < addCartItemButtons.length; i++){
    let button = addCartItemButtons[i]
    button.addEventListener('click', function(event){
        let buttonClicked = event.target
        let getProdId = buttonClicked.parentElement.parentElement.parentElement.getAttribute('data-prodid')
        let getTitle = buttonClicked.parentElement.parentElement.parentElement.querySelector('.product-title').innerText
        let getImage = buttonClicked.parentElement.parentElement.parentElement.querySelector('.product-header img').src
        let getColor = buttonClicked.parentElement.parentElement.querySelector('.product-description-text li span').innerText
        let getSize = buttonClicked.parentElement.parentElement.querySelector('.product-description-text li select').value
        let getPrice = buttonClicked.parentElement.parentElement.querySelector('.product-description-price').innerText
        let getSpan = buttonClicked.parentElement.parentElement.querySelector('li span').getAttribute('id')
        let oldItems = JSON.parse(localStorage.getItem('newProduct')) || [];
        let newItem = {
            'id': getProdId,
            'title': getTitle,
            'image': getImage,
            'color': getColor,
            'size': getSize,
            'price': getPrice,
            'spanid': getSpan,
        };
        
        if(localStorage.getItem('newProduct') == null) {
            oldItems.push(newItem);
            localStorage.setItem('newProduct', JSON.stringify(oldItems));
        } else {
            let data = JSON.parse(localStorage.getItem('newProduct'))
            let idCheck = data.filter(x => x.id === newItem.id).map(x => x.foo);
            let idCheckResults = idCheck.length
            if(idCheckResults > 0){
                alert('element already added')
            }else{
                oldItems.push(newItem);
                localStorage.setItem('newProduct', JSON.stringify(oldItems));
            }
        }
        let windowCartProducts = JSON.parse(window.localStorage.getItem("newProduct"));
        let productsInCart = document.getElementById('cartProducts')
        let productsAdded = 0
        for(let i = 0; i < windowCartProducts.length; i++){
            productsAdded = windowCartProducts.length
        }
        productsInCart.innerHTML = productsAdded + `<i class="fas fa-shopping-cart"></i>`
    })
} 
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!