Instead of adding a new object to the array, consider increasing the quantity of an existing object

I am new to working with a shopping cart component and my code is structured like this:

let cartCount = document.getElementById("counter");
let isItemSelected = false;
let itemCount = 0;
let shoppingCart = [];
let selectedSize = "";
let displaySelectedSize = document.getElementById("selected");
let displayCart = document.getElementById("cart");

selectItem = () => {  
  isItemSelected = true;
  selectedSize = event.srcElement.id;
  displaySelectedSize.innerHTML = `${selectedSize}`;
}

addItem = () => {
  if (isItemSelected === true) {

    const shopItem = {
      name: "Classic Tee",
      price: 75,
      size: `${selectedSize}`,
      quantity: 0
    }

    itemCount += 1;
    cartCount.innerHTML = `( ${itemCount} )`;    
    shopItem.quantity++;
    shoppingCart.push(shopItem);
    console.log(shoppingCart);

    return itemSuccess();
  } else {
      return itemError();
  }
}

My goal is for the shopItem.quantity to increase if I have multiple of the selected size.

Currently, I am getting this output:

// Output
0: {name: "Classic Tee", price: 75, size: "small", quantity: 1}
1: {name: "Classic Tee", price: 75, size: "small", quantity: 1}

// Desired Output
0: {name: "Classic Tee", price: 75, size: "small", quantity: 2}

I understand why my output looks like that, as a new object is created each time my addItem function runs. However, I want to update my shopItem.quantity if there are duplicates...

How can I achieve that?

Answer №1

To prevent conflicts, consider assigning an identity attribute to each item instead of relying on names. This can be done using the id property. Before adding an item, you can search for it in the collection. For instance, let's take a look at this sample item:

const cartItem = {id: 1, name: "Classic Tee"}

Prior to adding the item, you may check if it already exists in the shopping cart:

const existingItem = shoppingCart.find((item) => {
  return cartItem.id === item.id;
});

if(existingItem) {
   existingItem.quantity++;
} else {
  // Add the item to the cart
  shoppingCart.push(cartItem);
}

Answer №2

When managing your shoppingCart array, it may be helpful to filter and determine whether to add a new item or increase the quantity of an existing one.

Here's a simplified example to illustrate the concept:

let shoppingCart = [];

addItem = (newItem) => {
    function itemFilter(item) {
        return item.name === newItem.name && item.price === newItem.price && item.size === newItem.size
    }
    let existingItems = shoppingCart.filter(itemFilter)

    if (existingItems.length > 0) {
        existingItems[0].quantity += newItem.quantity
    } else {
        shoppingCart.push(newItem)
    }

}

const shopItem = {
    name: "Classic Tee",
    price: 75,
    size: "small",
    quantity: 1
}

const shopItem2 = {
    name: "Classic Tee",
    price: 75,
    size: "big",
    quantity: 1
}

const shopItem3 = {
    name: "Classic Tee",
    price: 75,
    size: "small",
    quantity: 2
}

console.log('-----------')
console.log(shoppingCart)
addItem(shopItem)
console.log('-----------')
console.log(shoppingCart)
addItem(shopItem)
console.log('-----------')
console.log(shoppingCart)
addItem(shopItem2)
console.log('-----------')
console.log(shoppingCart)
addItem(shopItem)
console.log('-----------')
console.log(shoppingCart)

Output:

-----------
[]
-----------
[ { name: 'Classic Tee', price: 75, size: 'small', quantity: 1 } ]
-----------
[ { name: 'Classic Tee', price: 75, size: 'small', quantity: 2 } ]
-----------
[ { name: 'Classic Tee', price: 75, size: 'small', quantity: 2 },
  { name: 'Classic Tee', price: 75, size: 'big', quantity: 1 } ]
-----------
[ { name: 'Classic Tee', price: 75, size: 'small', quantity: 4 },
  { name: 'Classic Tee', price: 75, size: 'big', quantity: 1 } ]

Answer №3

To implement a similar functionality using the reduce method, follow this example:

    const sampleList = [
        { value: 8, quantity: 1, cost: 3 },
        { value: 8, quantity: 1, cost: 3 },
        { value: 8, quantity: 1, cost: 3 },
        { value: 8, quantity: 1, cost: 3 },
        { value: 8, quantity: 1, cost: 3 },
        { value: 10, quantity: 1, cost: 12 },
    ];
    const reducerFunction = (obj, item) => {
        obj[item.value]
            ? (obj[item.value].quantity += 1)
            : (obj[item.value] = { ...item });
        return obj;
    };

    const hashmapArray = sampleList.reduce(reducerFunction, {});
    const mergedItems = Object.values(hashmapArray);
    console.log(mergedItems);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When using `v-if` in Vue, it is unable to directly access boolean values within arrays

After creating a vue component, I set up the data as shown below: data: function () { return { hwshow: [false, false, false, false, false, false, false, false, false, false], }; }, I also implemented a method to toggle these values: meth ...

Tips for extracting unique values from two arrays and returning them in a new array using JavaScript

Hello, I need assistance with combining two arrays. Array a contains [1,2,3] and array b contains [2,5]. I would like the result array to only include elements that are unique between the two arrays, such as [5]. Can you please provide guidance on how to ...

Infinite scrolling feature on Kendo UI mobile listview showcasing a single item at a time

Currently, I am utilizing the kendo ui mobile listview and encountering an issue when setting endlessScroll or loadMore to true. The problem arises as the listview only displays the first item in such instances. Upon inspecting with Chrome inspector, I ob ...

The JavaScript code is failing to retrieve any data from the API

import React, { Component } from 'react'; export class FetchData extends Component { static displayName = FetchData.name; constructor(props) { super(props); this.state = { users: [], loading: true }; } componentDidMount() { ...

Passing a one-dimensional array into std::thread is not possible

This example is derived from my current project, but I have created a simpler version for demonstration purposes (inspired by Lightness Races in Orbit). #include <thread> #include <iostream> class Foo { Foo(int n = 10) { size_ ...

disabling past dates in Bootstrap calendar

How can I disable past dates in Bootstrap easily? <script type="text/javascript"> $(function(){ $('.datepicker').datepicker(); }); </script> Date: <input type="text" class="datepicker"></input> I have added the ...

Sharing Global Variables in Node.js: What's the Best Way to Pass Them into Required Files?

Recently, I decided to organize my gulpfile.js by splitting it into multiple files within a /gulp folder. However, I encountered an issue when trying to pass a variable debug (boolean) into these files to control the behavior of the gulp command being incl ...

Get the JSON file from Firebase storage

My query boils down to this: Within my vue.js application, I am uploading a json file to a firebase storage bucket. However, when attempting to download the file for use within the app, I encounter an "Uncaught (in promise) undefined" error. The goal is t ...

Tips for Dynamically Binding Data in Angular ChartsWant to learn how to dynamically bind

I have integrated angular-charts directives into my application and everything works perfectly when initializing the data. However, I encountered an issue when reading the data from a JSON file and assigning it to the chart. The x-axis and y-axis are gener ...

Exploring data-toggle elements using jQuery

I am faced with the challenge of dynamically constructing a form using jQuery. The form includes a checkbox list of items that I am creating in the following manner: function initializeForm() { var html = ''; var items = GetItems(); for ( ...

Creating a variable in Python that can serve as an index for slicing another variable

Transitioning from a MATLAB background to Python, I am working on setting up a variable that contains a range of indices to slice an array. In MATLAB, this is how it's done: A = [2,3,4,5,6; 9,4,3,2,1; 5,4,3,2,5]; % some arbitrary matrix begin = 2; ...

How does the 'snack bar message' get automatically assigned without being explicitly defined in the 'data' function?

As a novice in web development and Vue, I am currently engaged in a simple project using Vuetify with Vue.JS 3. Within one of my views, there is a table that triggers a message and fetches status to display a snackbar to the user: methods: { async fetc ...

Struggling to connect with PouchDB within my HTML-based Web application

I am looking to integrate pouchDB into my WebApp so that upon clicking a button, the data from a JSON file will be saved to pouchDB. In the initial stage in my index.html, I included the following: <script type="module" src="pouchdb/packa ...

Switching the navigation menu using jQuery

I am looking to create a mobile menu that opens a list of options with a toggle feature. I want the menu list to appear when the toggle is clicked, and I also want to disable scrolling for the body. When the toggle menu is clicked again, the list should c ...

Display Vue component using a string input

Is there a solution to make this non-functioning example work, or is its usage illegal? Vue.component('hello', { template: '<span>Hello world!</span>' }) Vue.component('foo', { data(){ return { ...

Unable to locate the image file path in React.js

I'm having trouble importing images into my project. Even though I have saved them locally, they cannot be found when I try to import them. import {portfolio} from './portfolio.png' This leads to the error message: "Cannot find module &apos ...

Use a conditional statement for each element within the array

Below is the code I am currently using: if (res[0].toString() == "hello") { res[0] = "string"; }; While it works, I would like this logic to apply to all elements rather than just the first one. Is there a way to achieve this for every element in the ar ...

How can I retrieve an attribute from another model in Ember using the current handlebar in the HTML file?

I'm attempting to achieve the following: {{#if model.user.isAdmin}} <div> My name is {{model.user.name}} </div> {{/if}} within a handlebar that is being used in a controller unrelated to users: <script type="text/x-handlebars" data- ...

Grunt is throwing an error message of "Cannot GET/", and unfortunately ModRewrite is not functioning properly

I've recently started using Grunt (just began last Friday). Whenever I run Grunt Serve, it displays a page with the message "cannot GET/" on it. I tried implementing the ModRewrite fix but the error persists. Any assistance would be highly appreciat ...

Node/ejs not recognizing Javascript files

I have been working on implementing a JavaScript code to create a hamburger menu when the screen is at a specific size, but unfortunately, nothing seems to happen. Here is how my directory structure looks like: public imgs javascript menu. ...