If the size property varies while the ID keys remain constant, then the item can be added to the cart

I have implemented a cart insertion system that adds items to it based on specific rules:

Initially, I initialize an empty array for the cart items:

`let cartItems = [];`

Each item in the array is a Product object with defined properties:

{
"id": 10,
"name": "Nike Hoodie 1",
 ...
}

When adding a new item to the cartItems array, I want to increment the quantity property and set the size property if the item already exists in the array. If the new item's productSize differs from the existing item's productSize, I want to add the new item with quantity: 1.

The challenge arises when dealing with identical id properties for different products. This causes issues when trying to update or remove items from the cartItems array using the id. Any suggestions on how to resolve this?

I attempted assigning a temporaryId property with a random number for each product, but I'm unsure about its effectiveness. Here is the code snippet I came up with:

export const addItemToCart = (cartItems, cartItemToAdd, selectedSize) => {
  const existingCartItem = cartItems.find(
    (cartItem) => cartItem.id === cartItemToAdd.id
  );
  if (existingCartItem) {
    if (existingCartItem.productSize === selectedSize) {
      console.log('Product sizes match');
      return cartItems.map((cartItem) =>
        cartItem.id === cartItemToAdd.id
          ? {
              ...cartItem,
              quantity: cartItem.quantity + 1,
            }
          : cartItem
      );
    } else {
      console.log('Product sizes do not match');
      return cartItems.map((cartItem) =>
        cartItem.id === cartItemToAdd.id
          ? {
              ...cartItem,
              quantity: cartItem.quantity + 1,
              productSize: selectedSize,
            }
          : cartItem
      );
    }
  }
  let randomId = Math.floor(1000 + Math.random() * 9000);
  return [
    ...cartItems,
    {
      ...cartItemToAdd,
      tempId: randomId,
      quantity: 1,
      productSize: selectedSize,
    },
  ];
};

Answer №1

If you're looking for a way to update your existingCartItem check, consider modifying it to search for both the id and productSize of the item instead of just the id.

 const existingCartItemIndex = cartItems.findIndex((cartItem) => {
     return cartItem.id === cartItemToAdd.id && cartItem.productSize === selectedSize;
  });
});

This approach will allow you to determine whether the item already exists in the array or needs to be added based on the index value.

To implement this solution, you can use the following function:

export const addItemToCart = (cartItems, cartItemToAdd, selectedSize) => {
  const existingCartItemIndex = cartItems.findIndex((cartItem) => {
     return cartItem.id === cartItemToAdd.id && cartItem.productSize === selectedSize;
  });

  if (existingCartItemIndex > -1) {
     cartItems[existingCartItemIndex].quantity = cartItems[existingCartItemIndex].quantity + 1;
  } else {
    cartItems.push({ 
      ...cartItemToAdd, 
      quantity: 1, 
      productSize: selectedSize
  }

  return cartItems;
};

I hope this explanation is helpful!

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

Using jQuery to decrease the size of a div element containing an image

Hello everyone! I have an image inside a div and I am currently moving it down at a specific time using a delay. My question is, how can I make the image shrink as it moves down the screen until it eventually disappears completely at a set location? Curre ...

Tips for saving values created with JavaScript as an HTML file

I am looking to download an appended value as a HTML file. In my code, values are being appended from an external HTML file through an iframe. The code is functioning correctly and retrieving the right value. Now, I just need to download that appended valu ...

Encountering the issue: 'Unable to retrieve data: TypeError: Failed to fetch'

Encountering an issue while attempting to retrieve images from cloudinary which results in the error 'TypeError: Failed to fetch'. This problem is occurring within a MERN project. const fetchPosts = async () => { setLoading(true); try { ...

Utilizing React JS to Activate the Glyphicon Calendar Icon on Click

Could someone please advise on how to make the calendar glyphicon activate the datetime picker upon clicking? I have a button currently but it is not functional. I've been searching for React-specific solutions without success. <div className={cla ...

Creating a multi-step form in Rails without using the Wizard gem allows for more

My Rails 3.2.14 app gathers call data and the new/edit action form is quite lengthy on a single page. I am interested in implementing a multistep form using JS/client side processing to navigate between steps. While considering the Wicked Gem for multi-ste ...

Encountered error code 3228369023 while trying to establish a connection to a SQL Server database using Node.js with MSSQL

Currently in the process of setting up an API for a SQL Server Express database, my plan is to utilize mssql in Node.js with express to handle requests and communicate with the database. Despite trying several methods to establish a connection between my n ...

Tips for Disabling ML5 Posenet

Looking to halt Posenet after completing app task private sketch(p: any) { p.setup = () => { this.poseNet = ml5.poseNet(p.createCapture(p.VIDEO), { outputStride: 8 }); this.poseNet.on(&apos ...

Steps to automatically make jest mocked functions throw an error:

When using jest-mock-extended to create a mock like this: export interface SomeClient { someFunction(): number; someOtherFunction(): number; } const mockClient = mock<SomeClient>(); mockClient.someFunction.mockImplementation(() => 1); The d ...

Adding a context menu to a Leaflet map

Could someone provide guidance on how to add a custom context menu to a Leaflet map in Vue 3? I am currently utilizing [email protected], @vue-leaflet/[email protected], and experimenting with [email protected]. Here is a snippet of my code: ...

Tips for choosing a particular value in an HTML <script> query

Can someone please help me figure out how to select specific values in a form using a query? I'm trying to extract certain values like Hello and Lorem ipsum..., as well as Hi and Nullam fringilla... from the Content.join(''); section. I apo ...

Utilize the Tab feature effectively in Impress.Js

Currently, I have disabled the Tab key in Impress.js so that it only moves to the next slide. However, when I try to focus on links and delete this code to let it behave normally, Impress.js crashes. Has anyone found a workaround for this issue? Appreciat ...

Getting star ratings from the "rating" field in an array of objects using JavaScript

I am dealing with an array of objects that looks like this: var test_data = [ { "id" : "Test01", //Must be a string form ID "test_info" : "This is the test information", "tes ...

A function that checks if all numbers from 0 to n-1 are present in the given array, having a time complexity of O(n) and returning either 0 or 1

UPDATE: I accidentally omitted that I do not wish to assign another temporary array. I am tackling a challenge in C, where I am tasked with: Given an array 'a' and its size 'N', it is known that all elements in the array fall within th ...

Handlers for adjustments not correctly updating values in introduced object

I am facing an issue with a table that displays data fetched from an API and a select dropdown. Whenever a checkbox is selected, the name key along with its value is added to an array object named selectedFields. checkbox = ({ name, isChecked }) => { ...

Error: Trying to play the Snake Game with the P5.js Library, but getting the message "(X)

During my journey of coding a snake game by following a tutorial, I encountered an issue that the instructor had not faced before. Strangely enough, I am unable to identify the root cause of this problem. To aid in troubleshooting, I meticulously commente ...

Saving location points in a fixed array functions flawlessly, but storing them in a flexible array can cause the points to become corrupt

I've completed a snake game in C using ncurses. To determine the tail's position, I initially stored the snake's coordinates in a static array. However, it would be more logical to dynamically allocate an array equal to the size of the tail. ...

AngularJS: ng-repeat excluding duplicate keys

Here is a collection of objects I am working with: [{ key:test1 name: name1 }, { key:test1 name: name2 }, { key:test2 name: name3 }] I am currently using ng-repeat to showcase them: <tr ng-repeat=item in list> <td>{{item.key}}</td ...

Harnessing the power of JavaScript functions to display an image when clicked

Looking for help with making an image appear when clicking on one of three images? Despite trying different approaches, the desired result is still not achieved. I'm aware of using if else statements but exploring other methods. Any insights on what m ...

AngularJS Tutorial: Storing the Index Position of a JSON Object without Saving the Object Itself

My JSON data is as follows: $scope.myjson = [ {id: "1", name: "a"}, {id: "2", name: "b"}, {id: "3", name: "c", children: [{id: "4", name: "d"}]} ]; I am looking to store the position ...

The intricacies of JavaScript recursion explained thoroughly

I'm struggling to grasp how this recursion will function. Specifically, I can't seem to comprehend how the final console ('end'--) is being executed. Any guidance on the execution aspect would be greatly appreciated as I am having troub ...