Last active
February 16, 2020 04:20
-
-
Save IronGhost63/9a2e771a2c3539e79df1aea53908db08 to your computer and use it in GitHub Desktop.
Add or Update product (use Array.prototype.findIndex())
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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