Skip to content

Instantly share code, notes, and snippets.

@IronGhost63
Last active February 16, 2020 04:20
Show Gist options
  • Save IronGhost63/9a2e771a2c3539e79df1aea53908db08 to your computer and use it in GitHub Desktop.
Save IronGhost63/9a2e771a2c3539e79df1aea53908db08 to your computer and use it in GitHub Desktop.
Add or Update product (use Array.prototype.findIndex())
let products = [
{
id: 1,
quantity: 10,
},
{
id: 2,
quantity: 2,
}
];
const add_product = ( products, new_item ) => {
let index = products.findIndex( obj => obj.id == new_item.id );
if ( index > -1 ) {
products[index].quantity += new_item.quantity;
} else {
products.push( new_item );
}
return products;
}
products = add_product( products, {
id: 2,
quantity: 3,
} );
console.log( products );
products = add_product( products, {
id: 3,
quantity: 3,
} );
console.log( products );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment