简体   繁体   中英

How can I limit a JavaScript .filter result?

I'm creating a simple shopping cart in JavaScript as an exercise. I'm using.filter to remove a product (object) by ID when the user clicks to remove one item from the cart (array). However, of course, .filter will remove all objects with the ID of x from the array. I believe the best way to achieve what I'm looking for is to remove a maximum of one object with said ID from the array of objects. Is anyone aware of how to do this / a more apt solution?

JSFiddle: https://jsfiddle.net/LiamMacmillan/zryq62ua/79/

let thisItemId = $(this).parent().data("id");

shoppingCart = shoppingCart.filter(
    item => item.id != thisItemId
);

Use findIndex and splice :

const index = shoppingCart.findIndex(item => item.id === thisItemId);
if (index > -1) {
  shoppingCart.splice(index, 1);
}

It might be better to keep track of a count of each item in your shopping cart though, will be much easier to display to the user, and makes this situation simpler to manage.

an example of what this might look like

let shoppingCart = [
  { itemId: 1, count: 5 },
  { itemId: 2, count: 3 }
];

function decreaseCount(itemId) {
  const shoppingCartItem = shoppingCart.find(x => x.itemId === itemId);
  if (shoppingCartItem) {
    if (--shoppingCartItem.count < 1) {
      removeItem(itemId);
    }
  }
}

// slightly less efficient, but uses immutable objects, map, and filter
function decreaseCountImmutable(itemId) {
  shoppingCart = 
   shoppingCart
     .map(x =>  x.itemId !== itemId ? x: ({ ...x, count: x.count -1 }))
     .filter(x => x.count > 0);
}

function increaseCount(itemId) {
  const shoppingCartItem = shoppingCart.find(x => x.itemId === itemId);
  if (shoppingCartItem) {
    shoppingCartItem.count++;
  } else {
    shoppingCart.push({ itemId, count: 1 });
  }
}

// uses immutable objects and map
function increaseCountImmutable(itemId) {
  let foundItem = false;
  shoppingCart = shoppingCart.map(x =>  x.itemId !== itemId ? x: (foundItem = true) && ({ ...x, count: x.count + 1 }));
  if (!foundItem) {
    shoppingCart.push({ itemId, count: 1 });
  } 
}

function removeItem(itemId) {
  shoppingCart = shoppingCart.filter(x => x.itemId !== itemId);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM