Alanaj
Alanaj

Reputation: 247

Having trouble stopping duplicate from being added to array

I have added an voice command prompt to my small ecommerce application. When I command the ai to add a product to the list it adds it and when I try to add it again it doesn't. However, when I try to add a different item the command prompt denies it. I want it to work for all item. I have tried to look up different options including indexOf but that method isn't working either.

 

function voiceCommand(data) {
const products = new Products();

let alanBtnInstance = alanBtn({
    top: '15px',
    left: '15px',
    onCommand: function (commandData) {
        if (commandData.command === "opencart") {
            products.openCart();
        }

        else if (commandData.command === "closecart") {
            products.closeCart();
        }

        else if (commandData.command === "addItem") {
            // get cart Items to compare to commandData.name
            const cartItem = data
            cartItem.forEach(item => {
                return item.amount = 1
            });

            const item = cartItem.map(item => item)
                .find(item => item.title.toLowerCase() === commandData.name.toLowerCase());

            cart = [...cart, item]


            function hasDuplicates(arr) {
                return new Set(arr).size !== arr.length;
            }


            if (hasDuplicates(cart)) {

                alanBtnInstance.playText(`${item.title} is already in cart`);
                return
            }
            else {

                const buttons = [...document.querySelectorAll('.cart-btn')]
                buttonsDOM = buttons;
                buttons.forEach(button => {
                    let id = button.dataset.id;
                    let inCart = cart.find(item => item.id === Number(id));

                    if (inCart) {
                        button.innerText = "In Cart";
                        button.disabled = true;
                    }
                });
                products.addCartItem(item);
                products.setCartValues(cart);
                products.openCart()
                return
            }
        }
    },
    rootEl: document.getElementById("alan-btn"),
});
}

Upvotes: 0

Views: 74

Answers (1)

Daniil Loban
Daniil Loban

Reputation: 4381

I simplified the code a little to show the basic principle (I hope I was not mistaken in the logic)

let cart = [];

const addItem = (data, commandData) => {

  const item = data
    .find(item => item.title.toLowerCase() ===                   
      commandData.name.toLowerCase());
  const dup = cart
     .find(item => item.title.toLowerCase() ===
       commandData.name.toLowerCase());

  if (dup) {
     //console.log(`${dup.title} is already in cart`)
     dup.amount += 1;  // just change amount
     item.amount -= 1; // calc rest in store
  } else {
     cart = [...cart, {...item, amount: 1}] // insert new
     item.amount -= 1; // calc rest in store
  }
} 

// store with amounts 
const data = [
  {id:'0', amount: '100', title: 'a'},
  {id:'0', amount: '100', title: 'b'}
]

console.log('Cart before:')
console.log(JSON.stringify(cart))
console.log('Store before:')
console.log(JSON.stringify(data))

// test actions:
addItem(data, {name: 'b'}) 
addItem(data, {name: 'b'})
addItem(data, {name: 'a'})
 
console.log('Cart after:')
console.log(JSON.stringify(cart))
console.log('Store after:')
console.log(JSON.stringify(data))

I think your code should be like this:

    else if (commandData.command === "addItem") {
        // get cart Items to compare to commandData.name
        const cartItem = data;
        
        cartItem.forEach(item => {
          return item.amount = 1
        });

        const item = cartItem.find(item => item.title.toLowerCase() === commandData.name.toLowerCase());
        const dup = cart.find(item => item.title.toLowerCase() === commandData.name.toLowerCase());

        if (dup) {
            alanBtnInstance.playText(`${item.title} is already in cart`);
            return
        }
        else {
            cart = [...cart, item]
            const buttons = [...document.querySelectorAll('.cart-btn')]
            buttonsDOM = buttons;
            buttons.forEach(button => {
                let id = button.dataset.id;
                let inCart = cart.find(item => item.id === Number(id));

                if (inCart) {
                    button.innerText = "In Cart";
                    button.disabled = true;
                }
            });
            products.addCartItem(item);
            products.setCartValues(cart);
            products.openCart()
            return
        }
    }

Upvotes: 1

Related Questions