I am trying to create cart using js
function fuBuyNow() {
var prodqty = 1;
var prodid = localStorage.ls_productID;
var prodprice = $('#ppriceoffer').html();
var cartItem = {
productid: prodid,
productqty: prodqty,
productprice: prodprice
};
var cartItemJSON = JSON.stringify(cartItem);
console.log(cartItemJSON);
var cartArray = new Array();
// If javascript shopping cart session is not empty
if (localStorage.getItem('shopping-cart')) {
cartArray = JSON.parse(localStorage.getItem('shopping-cart'));
}
cartArray.push(cartItemJSON);
var cartJSON = JSON.stringify(cartArray);
localStorage.setItem('shopping-cart', cartJSON);
}
now i have cart data in an array, I want to sum of productid
= 10005, productid
= 10001 price and create new array
var obj = "[{"slno":"1","productid":"10001","qty":"1","price":"250"},{"slno":"2","productid":"10005","qty":"1","price":"350"},{"slno":"3","productid":"10001","qty":"1","price":"250"},{"slno":"4","productid":"10003","qty":"1","price":"450"},{"slno":"5","productid":"10005","qty":"1","price":"350"}]";
2
Answers
You can achieve this by using JavaScript’s array methods along with jQuery if you’re working with DOM elements. Here’s how you can do it:
This code filters the original array to include only items with productid equal to "10005" or "10001", then calculates the total price of those items, and finally creates a new array with the total price. You can use this newArray to display or manipulate the total price as needed. If you have any further questions, feel free to ask!
Update 1:
try this
the product ids are in string format and needs a type assertion to int with ParseInt() function . you can index over them afterwards , add them and store in a new array . there are so many different of doing so with js builtin methods and functions , but i saw this one easy.