Problems with calculating total price in cart - javascript

I'm trying to calculate the total price of my cart. It works when I only select the same product but when I chose another product it just multiplies the number of clicks to the total price. How can I rewrite this so it doesn't multiply the amount of clicks?
GIF of my problem: https://gyazo.com/c273f1d8a3caa3cded6debef52cfadaf
const shopContainer = document.querySelector(".shop-content");
let productTitle;
let productDescription;
let productImage;
let productPrice;
let productCategory;
let productId;
let productKey = [];
let productArray = [];
let output = "";
const url = "https://fakestoreapi.com/products";
let data = fetch(url)
.then((res) => res.json())
.then((data) => {
for (let i = 0; i < data.length; i++) {
productTitle = data[i].title;
productDescription = data[i].description;
productImage = data[i].image;
productPrice = data[i].price;
productCategory = data[i].category;
productId = data[i].id;
productArray[i] = [
productTitle,
productDescription,
productImage,
productPrice,
productCategory,
productId,
];
productKey[i] = data[i].id;
localStorage.setItem(productKey[i], JSON.stringify(productArray[i]));
}
showApi();
})
.catch((error) => {
console.error("Error message:", error);
});
function showApi() {
for (let i = 0; i < productArray.length; i++) {
productId = productArray[i][5];
output += `
<div class="product-box">
<img class="product" src="${productArray[i][2]}" alt="product image">
<h2 class="product-title">${productArray[i][0]}</h2>
<div class="bottom-box">
<span class="price">${productArray[i][3]}$</span>
<i class='bx bx-shopping-bag add-cart' "data-id="${productId}" onclick="returnKey(${productArray[i][5]})"></i>
</div>
</div>
`;
}
shopContainer.innerHTML = output;
}
let inputCart = document.querySelector(".inputCart");
function returnKey(clickedId) {
cart.classList.add("active");
console.log(clickedId);
if (localStorage.length !== 0) {
let sum = 0;
Object.keys(localStorage).forEach(function (key) {
productObject = JSON.parse(localStorage.getItem(key));
completeProduct = productObject;
sum += completeProduct[3];
if (completeProduct[5] == clickedId) {
let cartPrice = document.createElement("p");
let cartTitle = document.createElement("p");
let cartImage = document.createElement("img");
inputCart.appendChild(cartPrice);
inputCart.appendChild(cartImage);
inputCart.appendChild(cartTitle);
cartPrice.setAttribute("class", "cart-price")
cartTitle.setAttribute("class", "cart-title");
cartImage.setAttribute("src", completeProduct[2]);
cartImage.setAttribute("width", "75");
cartImage.setAttribute("height", "75");
cartTitle.innerHTML = completeProduct[0];
cartPrice.innerHTML = "$" + completeProduct[3];
console.log(cartPrice);
console.log(cartTitle);
document.getElementById('priceTotal').innerHTML = "Total: " + sum + "$";
console.log(sum)
}
})
}
};
// function totalSum(cartPrice) {
// sum = 0;
// cartPrice = document.querySelectorAll(".cart-price");
// for (let i = 0; i < cartPrice.length; i++) {
// sum = sum + completeProduct[3];
// console.log("Product price " + sum);
// document.getElementById('priceTotal').innerHTML = "Total: " + sum + "$";
// }
// }
let removeBtn = document.getElementById("removeBtn").addEventListener("click", clearCart);
let buyBtn = document.getElementById("buyBtn").addEventListener("click", buyCart);
function clearCart() {
removeCart = window.confirm("Are you sure you want to clear your cart?");
if (removeCart) {
inputCart.innerHTML = "";
document.getElementById('priceTotal').innerHTML = "Total: " + "0" + "$";;
console.clear();
}
};
function buyCart() {
shopMore = window.confirm("Do you want to checkout?");
if (shopMore) {
alert("Thank your for shopping at CatchShop!");
window.location.reload();
}
};
let cartIcon = document.querySelector("#cart-icon");
let cart = document.querySelector(".cart");
let closeCart = document.querySelector("#close-cart");
cartIcon.onclick = () => {
cart.classList.add("active");
};
closeCart.onclick = () => {
cart.classList.remove("active");
};
Thanks in advance! :)

You are calling the totalSum() function for every item. And sum always gets "reset" to 0. Try to add let sum = 0 before this line Object.keys(localStorage).forEach(function (key) {
function totalSum() {
cartPrice = document.querySelectorAll(".cart-price");
let sum = 0; // Everytime this function gets called, sum gets reset
for (let i = 0; i < cartPrice.length; i++) {
sum = sum + completeProduct[3];
console.log(sum);
document.getElementById('priceTotal').innerHTML = "Total: " + sum + "$";
}
}
Solution:
let inputCart = document.querySelector(".inputCart");
function returnKey(clickedId) {
cart.classList.add("active");
console.log(clickedId);
if (localStorage.length !== 0) {
let sum = 0;
Object.keys(localStorage).forEach(function (key) {
productObject = JSON.parse(localStorage.getItem(key));
completeProduct = productObject;
if (completeProduct[5] == clickedId) {
let cartPrice = document.createElement("p");
let cartTitle = document.createElement("p");
let cartImage = document.createElement("img");
inputCart.appendChild(cartPrice);
inputCart.appendChild(cartImage);
inputCart.appendChild(cartTitle);
cartPrice.setAttribute("class", "cart-price")
cartTitle.setAttribute("class", "cart-title");
cartImage.setAttribute("src", completeProduct[2]);
cartImage.setAttribute("width", "75");
cartImage.setAttribute("height", "75");
cartTitle.innerHTML = completeProduct[0];
cartPrice.innerHTML = "$" + completeProduct[3];
console.log(cartPrice);
console.log(cartTitle);
totalSum(sum);
}
})
}
};
function totalSum(sum) {
cartPrice = document.querySelectorAll(".cart-price");
for (let i = 0; i < cartPrice.length; i++) {
sum = sum + completeProduct[3];
console.log(sum);
document.getElementById('priceTotal').innerHTML = "Total: " + sum + "$";
}
}
Edit Solution:
You don't even need the totalSum function. You can simply increase the value of the sum variable with the current price of the local storage object you are iterating.
let inputCart = document.querySelector(".inputCart");
function returnKey(clickedId) {
cart.classList.add("active");
console.log(clickedId);
if (localStorage.length !== 0) {
let sum = 0;
Object.keys(localStorage).forEach(function (key) {
productObject = JSON.parse(localStorage.getItem(key));
completeProduct = productObject;
sum += completeProduct[3];
if (completeProduct[5] == clickedId) {
let cartPrice = document.createElement("p");
let cartTitle = document.createElement("p");
let cartImage = document.createElement("img");
inputCart.appendChild(cartPrice);
inputCart.appendChild(cartImage);
inputCart.appendChild(cartTitle);
cartPrice.setAttribute("class", "cart-price")
cartTitle.setAttribute("class", "cart-title");
cartImage.setAttribute("src", completeProduct[2]);
cartImage.setAttribute("width", "75");
cartImage.setAttribute("height", "75");
cartTitle.innerHTML = completeProduct[0];
cartPrice.innerHTML = "$" + completeProduct[3];
console.log(cartPrice);
console.log(cartTitle);
document.getElementById('priceTotal').innerHTML = "Total: " + sum + "$";
}
})
}
};
Edit:
function returnKey(clickedId) {
cart.classList.add("active");
console.log(clickedId);
if (localStorage.length !== 0) {
Object.keys(localStorage).forEach(function (key) {
productObject = JSON.parse(localStorage.getItem(key));
completeProduct = productObject;
if (completeProduct[5] == clickedId) {
let cartPrice = document.createElement("p");
let cartTitle = document.createElement("p");
let cartImage = document.createElement("img");
inputCart.appendChild(cartPrice);
inputCart.appendChild(cartImage);
inputCart.appendChild(cartTitle);
cartPrice.setAttribute("class", "cart-price")
cartTitle.setAttribute("class", "cart-title");
cartImage.setAttribute("src", completeProduct[2]);
cartImage.setAttribute("width", "75");
cartImage.setAttribute("height", "75");
cartTitle.innerHTML = completeProduct[0];
cartPrice.innerHTML = "$" + completeProduct[3];
console.log(cartPrice);
console.log(cartTitle);
let cartElements = document.getElementsByClassName('cart-price');
let sum = 0;
for (let i = 0; i < cartElements.length; ++i) {
let item = cartElements[i];
let price = item.innerText;
// Get rid of the $ sign and convert it to int
sum += parseInt(price.slice(1));
}
let inputCart = document.querySelector(".inputCart");
document.getElementById('priceTotal').innerHTML = "Total: " + sum + "$";
}
})
}
};

You are rewriting the innerHTML of the priceTotal element with the current sum value every cycle of the for loop.

Related

Add delay when index++ (increase)

I created a type writer effect with JavaScript but I would like when the word change add delay before the function increase index
const texts = ["Front Developer", "Designer", "Human"];
let count = 0;
let index = 0;
let currentText = '';
let letter = '';
(function type(){
if(count === texts.length){
count = 0;
}
currentText = texts[count];
letter = currentText.slice(0, index++);
document.querySelector('.typing').textContent = letter;
if(letter.length === currentText.length){
count++;
index = 0;
}
setTimeout(type, 400);
}());
<span>I'm <span class="typing"></span></span>
Try return with different timeout
const texts = ["Front Developer", "Designer", "Human"];
let count = 0;
let index = 0;
let currentText = '';
let letter = '';
(function type() {
if (count === texts.length) {
count = 0;
}
currentText = texts[count];
letter = currentText.slice(0, index++);
document.querySelector('.typing').textContent = letter;
if (letter.length === currentText.length) {
count++;
index = 0;
setTimeout(type, 2000);
return;
}
setTimeout(type, 200);
}());
<span>I'm <span class="typing"></span></span>
Here a solution with async / await
const texts = ["Front Developer", "Designer", "Human"];
let count = 0;
let index = 0;
let currentText = '';
let letter = '';
(async function type(){
if(count === texts.length){
count = 0;
}
currentText = texts[count];
letter = currentText.slice(0, index++);
document.querySelector('.typing').textContent = letter;
if(letter.length === currentText.length){
count++;
index = 0;
await sleep(4000);
}
await sleep(30);
type();
}());
function sleep(time) { return new Promise(res => setTimeout(res, time))}
<span>I'm <span class="typing"></span></span>

how can I stop it from printing duplicate?

I'm I've created the below shopping cart, however, I'm trying to print the elements of the basket inside the HTML, but it's printing duplicated. If I add another element to the basket, it prints the new one + the previous one, even if the previous one is already printed.
Really appreciate the help, i'm new with JS, so struggling a bit.
thank you
//list of products
let products = [
{
name: "Logitech Pebble M350 Pink",
tag: "mouse",
price: 15.99,
count: ""
},
{
name: "Logitech K380 Multi-Device Bluetooth Keyboard",
tag: "keyboard",
price: 20.99,
count: ""
},
{
name: "Anker SoundCore min",
tag: "speaker",
price: 22.99,
count: ""
}
];
//ADD
function add() {
let quantity = document.getElementsByClassName("quantity");
let totalPrice = [];
let nameCount = 0;
let basket = [];
let basketSentence = document.getElementById("yourBasket");
for (let i = 0; i < quantity.length; i++) {
products[i].count = quantity[i].value;
}
for (var name in products) {
nameCount = nameCount + 1;
}
for (let i = 0; i < nameCount; i++) {
totalPrice[i] = products[i].price * products[i].count;
var sum = totalPrice.reduce(function(a, b) {
return a + b;
}, 0);
if (products[i].count != 0) {
basket.push(products[i]);
const newLi = document.createElement("li");
newLi.innerText = products[i].count + " " + products[i].name;
if (yourBasket.innerText != newLi.innerText) {
yourBasket.append(newLi);
console.log(yourBasket.innerText);
}
}
document.getElementById("total-value").innerHTML = sum;
}
}
//REMOVE
let removeBtn = document.querySelectorAll(".remove");
let quantity = document.querySelectorAll(".quantity");
removeBtn.forEach(function(check) {
check.addEventListener("click", checkIndex);
});
function checkIndex(event) {
let totalPrice = [];
let nameCount = 0;
var index = Array.from(removeBtn).indexOf(event.target);
console.log(index);
quantity[index].value = "";
products[index].count = quantity[index].value;
console.log(products[index].count);
for (var name in products) {
nameCount = nameCount + 1;
}
for (let i = 0; i < nameCount; i++) {
totalPrice[i] = products[i].price * products[i].count;
var sum = totalPrice.reduce(function(a, b) {
return a + b;
}, 0);
document.getElementById("total-value").innerHTML = sum;
}
}
Explanation
The solution is to reset the text of the basket before you start appending again.
Add the line yourBasket.innerHTML = ""; before the for loop.
The problem was that append was appending text. What you want is to actually clear the basket, and re-append all the totals of all the products.
Excerpt:
yourBasket.innerHTML = ""; //THIS IS THE LINE
for (let i = 0; i < nameCount; i++) {
totalPrice[i] = products[i].price * products[i].count;
Full code for Add:
//ADD
function add() {
let quantity = document.getElementsByClassName("quantity");
let totalPrice = [];
let nameCount = 0;
let basket = [];
let basketSentence = document.getElementById("yourBasket");
for (let i = 0; i < quantity.length; i++) {
products[i].count = quantity[i].value;
}
for (var name in products) {
nameCount = nameCount + 1;
}
yourBasket.innerHTML = ""; //(newLi);
for (let i = 0; i < nameCount; i++) {
totalPrice[i] = products[i].price * products[i].count;
var sum = totalPrice.reduce(function(a, b) {
return a + b;
}, 0);
if (products[i].count != 0) {
basket.push(products[i]);
const newLi = document.createElement("li");
newLi.innerText = products[i].count + " " + products[i].name;
if (yourBasket.innerText != newLi.innerText) {
yourBasket.append(newLi);
console.log(yourBasket.innerText);
}
}
document.getElementById("total-value").innerHTML = sum;
}
}
JSFiddle: https://jsfiddle.net/4zyd1sow/4/

Javascript , sum of key pair value's

anyone have a solution to add up these key pair values for the one key? I've tried to add them to the key pair value using dict[id] += parseFloat(value) but it results in incorrect operation. I've tried using eval(valuestring), I'm pretty sure the value's inside the key are still a string. Need to get the sum of each ID for a leaderboard.
Any help is much appreciated.
Output of keys of dict_tips
'["U5WUV3A3G"]': '1000.0,200.0,300.0,100.0,500.0,420.0,42.0,98.0,500.0,150.0,300.0,300.0,25.0,200.0,',
'["U5FHMCWP7"]': '50.0,500.0,1000.0,45.0,1000.0,100.0,15.0,3.0,675.0,100.0,225.0,25.0,900.0,100.0,1000.0,10.0,30.0,0.001,0.005,1.755,1.724,1.5,',
'["U5SJQMME3"]': '100000.,100.0,100.0,100.0,50.0,100.0,100.0,40000.0,10.0,200.0,500.0,',
'["U6KAYAJ5Q"]': '100.0,200.0,900.0,100.0,100.0,100.0,1000.0,10.0,10.0,1000.0,100.0,100.0,1.0,10.0,800.0,200.0,100.0,190.0,190.0,10.0,10.0,',
'["U6F1AHQ8H"]': '10.0,100.0,',
'["U3H65TS9K"]': '500.0,100.0,200.0,500.0,35.414,12.345,',
'["U5HUZG3MF"]': '1.0,0.5,42.0,44.0,1.0,1.0,7.995,100.0,100.0,100.0,50.0,100.0,4.0,5.0,5.0,5.0,5.0,5.0,',
'["U5ZPTLXV5"]': '5.0,',
'["U6EMQC2LF"]': '737.998,2000.0,1000.0,300.0,666.0,6000.0,5000.0,5000.0,1000.0,5000.0,999.0,1.0,5000.0,3000.0,5000.0,9999.0,',
'["U62EVB2P7"]': '50.0,20.0,100.0,1.0,100.0,50.0,100.0,50.0,100.0,100.0,1.0,',
'["U3GJ9SREZ"]': '150.0,100.0,100.0,100.0,',
'["U6F0KBT2P"]': '1000.0,100.0,1000.0,100.0,800.0,100.0,100.0,',
'["U5WD17D5E"]': '150.0,75.0,',
'["U697Y6BL3"]': '5.0,1.0,51.0,2.0,1.0,1.0,5.0,',
'["U6GU038HX"]': '4000.0,',
'["U4B0NK2NR"]': '100.0,500.0,200.0,100.0,100.0,100.0,100.0,',
'["U6C23F8MT"]': '49.0,100.0,',
'["U5KQY01ST"]': '105.0,',
'["U6FSC0CC8"]': '100.0,100.0,',
'["U659939GF"]': '20.0,100.0,100.0,100.0,',
'["U5URNPRSA"]': '5.0,20.0,5.0,5.0,50.0,',
'["U5VAMV76F"]': '0.5,20.0,200.0,200.0,200.0,200.0,100.0,200.0,5.0,500.0,200.0,50.0,',
'["U5UL7KWKU"]': '150.0,200.0,',
'["U61NYHM25"]': '64.0,2.0,',
'["U6CMX965S"]': '10.0,10.0,20.0,50.0,30.0,',
'["U5G40R5PF"]': '499.0,',
'["U4XHS3DHA"]': '51.0,',
'["U69MY9WDS"]': '10.0,6.414,10.0,10.0,',
'["U666S65RC"]': '100.0,100.0,',
'["U5X3MEZ39"]': '1.0,1.0,10.01,10.1,0.002,0.01,1.1,' ]
Core
var dict_tips = [];
var dict_counts = [];
var sum = []
for (var i = 0; i < 200 ; i++) {
var str = res.messages.matches[i].text;
var stdout = capcon.captureStdout(function scope() {
for (var x = 46 ; x < 55 ; x++) {
process.stdout.write(str[x]);
}
});
var id = JSON.stringify(stdout.match(/.{1,9}/g))
var stdout = capcon.captureStdout(function scope() {
for (var x = 76 ; x < 85 ; x++) {
process.stdout.write(str[x]);
} });
var extract = JSON.stringify(stdout.match(/.{1,9}/g));
var parse = extract.indexOf(/.RDD|RD|R|D|:| /g)
var x = checkAndAdd(id,extract)
function checkAndAdd(id,extract) {
var found = dict_tips.some(function (el) {
return el.key === id; })
if (!found) { if (parse = -1)
{
var format = ( ""+extract.slice(2,9)).replace(/.RDD|RD|R|D|:| /g,'');
var x = format.substr(0, 9) + " " + format.substr(9);
var total = x.split(" ")
dict_tips.push({key: id})
dict_tips[id] += total
}
else
{
var format = extract.slice(2,9)
var x = format.substr(0, 9) + " " + format.substr(9)
var total = x.split(" ")
dict_tips.push({key: id})
dict_tips[id] = "";
dict_tips[id] += total
}
}
else
{
var extract = stdout.match(/.{1,9}/g);
var parse = extract.indexOf(/.RDD|RD|R|D|:| /g)
if (parse = -1)
{
var format = ( "" + extract).replace(/.RDD|RD|R|D|:| /g,'');
var x = format.substr(0, 9) + " " + format.substr(9);
var total = x.split(" ")
dict_tips[id] += total
}
else
{
var format = extract.slice(1,9)
var x = format.substr(0, 9) + " " + format.substr(9);
var total = x.split(" ")
dict_tips[id] += total
};
}
}
}
var sum = dict_tips.reduce(function(a, b) { return a + b; }, 0);
console.log(JSON.stringify(sum))
console.log(dict_tips)
Split the string, then parseFloat and sum up the values:
const data = {
'["U5WUV3A3G"]': '1000.0,200.0,300.0,100.0,500.0,420.0,42.0,98.0,500.0,150.0,300.0,300.0,25.0,200.0,',
'["U5FHMCWP7"]': '50.0,500.0,1000.0,45.0,1000.0,100.0,15.0,3.0,675.0,100.0,225.0,25.0,900.0,100.0,1000.0,10.0,30.0,0.001,0.005,1.755,1.724,1.5,',
'["U5SJQMME3"]': '100000.,100.0,100.0,100.0,50.0,100.0,100.0,40000.0,10.0,200.0,500.0,',
'["U6KAYAJ5Q"]': '100.0,200.0,900.0,100.0,100.0,100.0,1000.0,10.0,10.0,1000.0,100.0,100.0,1.0,10.0,800.0,200.0,100.0,190.0,190.0,10.0,10.0,',
'["U6F1AHQ8H"]': '10.0,100.0,',
'["U3H65TS9K"]': '500.0,100.0,200.0,500.0,35.414,12.345,',
'["U5HUZG3MF"]': '1.0,0.5,42.0,44.0,1.0,1.0,7.995,100.0,100.0,100.0,50.0,100.0,4.0,5.0,5.0,5.0,5.0,5.0,',
'["U5ZPTLXV5"]': '5.0,',
'["U6EMQC2LF"]': '737.998,2000.0,1000.0,300.0,666.0,6000.0,5000.0,5000.0,1000.0,5000.0,999.0,1.0,5000.0,3000.0,5000.0,9999.0,',
'["U62EVB2P7"]': '50.0,20.0,100.0,1.0,100.0,50.0,100.0,50.0,100.0,100.0,1.0,',
'["U3GJ9SREZ"]': '150.0,100.0,100.0,100.0,',
'["U6F0KBT2P"]': '1000.0,100.0,1000.0,100.0,800.0,100.0,100.0,',
'["U5WD17D5E"]': '150.0,75.0,',
'["U697Y6BL3"]': '5.0,1.0,51.0,2.0,1.0,1.0,5.0,',
'["U6GU038HX"]': '4000.0,',
'["U4B0NK2NR"]': '100.0,500.0,200.0,100.0,100.0,100.0,100.0,',
'["U6C23F8MT"]': '49.0,100.0,',
'["U5KQY01ST"]': '105.0,',
'["U6FSC0CC8"]': '100.0,100.0,',
'["U659939GF"]': '20.0,100.0,100.0,100.0,',
'["U5URNPRSA"]': '5.0,20.0,5.0,5.0,50.0,',
'["U5VAMV76F"]': '0.5,20.0,200.0,200.0,200.0,200.0,100.0,200.0,5.0,500.0,200.0,50.0,',
'["U5UL7KWKU"]': '150.0,200.0,',
'["U61NYHM25"]': '64.0,2.0,',
'["U6CMX965S"]': '10.0,10.0,20.0,50.0,30.0,',
'["U5G40R5PF"]': '499.0,',
'["U4XHS3DHA"]': '51.0,',
'["U69MY9WDS"]': '10.0,6.414,10.0,10.0,',
'["U666S65RC"]': '100.0,100.0,',
'["U5X3MEZ39"]': '1.0,1.0,10.01,10.1,0.002,0.01,1.1,'
}
const sums = Object.keys(data).reduce((results, key) => {
results[key] = data[key].split(',')
.map(item => parseFloat(item))
.filter(item => !isNaN(item))
.reduce((res, item) => res + item, 0)
return results
}, {})
console.log(sums)
In PHP, you would do an explode on the commas, think for javascript its split. After you would run a loop through each index of the array that the split function just created and adding to a total sum. You would need to do a parsefloat on each value of the index as well.
You can simply iterate through the keys of the data using for in.
Then you need to split the string into an array, and sum up the values using reduce.
const data = {
'["U5WUV3A3G"]': '1000.0,200.0,300.0,100.0,500.0,420.0,42.0,98.0,500.0,150.0,300.0,300.0,25.0,200.0,',
'["U5FHMCWP7"]': '50.0,500.0,1000.0,45.0,1000.0,100.0,15.0,3.0,675.0,100.0,225.0,25.0,900.0,100.0,1000.0,10.0,30.0,0.001,0.005,1.755,1.724,1.5,',
'["U5SJQMME3"]': '100000.,100.0,100.0,100.0,50.0,100.0,100.0,40000.0,10.0,200.0,500.0,',
'["U6KAYAJ5Q"]': '100.0,200.0,900.0,100.0,100.0,100.0,1000.0,10.0,10.0,1000.0,100.0,100.0,1.0,10.0,800.0,200.0,100.0,190.0,190.0,10.0,10.0,',
'["U6F1AHQ8H"]': '10.0,100.0,',
'["U3H65TS9K"]': '500.0,100.0,200.0,500.0,35.414,12.345,',
'["U5HUZG3MF"]': '1.0,0.5,42.0,44.0,1.0,1.0,7.995,100.0,100.0,100.0,50.0,100.0,4.0,5.0,5.0,5.0,5.0,5.0,',
'["U5ZPTLXV5"]': '5.0,',
'["U6EMQC2LF"]': '737.998,2000.0,1000.0,300.0,666.0,6000.0,5000.0,5000.0,1000.0,5000.0,999.0,1.0,5000.0,3000.0,5000.0,9999.0,',
'["U62EVB2P7"]': '50.0,20.0,100.0,1.0,100.0,50.0,100.0,50.0,100.0,100.0,1.0,',
'["U3GJ9SREZ"]': '150.0,100.0,100.0,100.0,',
'["U6F0KBT2P"]': '1000.0,100.0,1000.0,100.0,800.0,100.0,100.0,',
'["U5WD17D5E"]': '150.0,75.0,',
'["U697Y6BL3"]': '5.0,1.0,51.0,2.0,1.0,1.0,5.0,',
'["U6GU038HX"]': '4000.0,',
'["U4B0NK2NR"]': '100.0,500.0,200.0,100.0,100.0,100.0,100.0,',
'["U6C23F8MT"]': '49.0,100.0,',
'["U5KQY01ST"]': '105.0,',
'["U6FSC0CC8"]': '100.0,100.0,',
'["U659939GF"]': '20.0,100.0,100.0,100.0,',
'["U5URNPRSA"]': '5.0,20.0,5.0,5.0,50.0,',
'["U5VAMV76F"]': '0.5,20.0,200.0,200.0,200.0,200.0,100.0,200.0,5.0,500.0,200.0,50.0,',
'["U5UL7KWKU"]': '150.0,200.0,',
'["U61NYHM25"]': '64.0,2.0,',
'["U6CMX965S"]': '10.0,10.0,20.0,50.0,30.0,',
'["U5G40R5PF"]': '499.0,',
'["U4XHS3DHA"]': '51.0,',
'["U69MY9WDS"]': '10.0,6.414,10.0,10.0,',
'["U666S65RC"]': '100.0,100.0,',
'["U5X3MEZ39"]': '1.0,1.0,10.01,10.1,0.002,0.01,1.1,'
}
let sum = {};
for (var key in data) {
let arr = data[key].split(',');
let total = arr.reduce((acc, curr) => {
if (parseInt(curr)) {
return acc + parseInt(curr);
}
return acc;
}, 0);
sum[key] = total;
}
console.log(sum)

Function that console.log's the total of all items together

I want to create a function called totalPriceCheck that console.log's the total of all shoppingCart items together.
var shoppingCart = [];
function addToCart (name, price) {
var object = {};
object.name = name;
object.price = price;
shoppingCart.push(object);
}
function priceCheck(item){
for (var i = 0; i < shoppingCart.length; i += 1) {
if (item === shoppingCart[i].name) {
console.log(shoppingCart[i].price + " sheqalim");
} else {
console.log("the searched item is not in the shopping cart array!");
}
}
}
function totalPriceCheck(){
for (var i = 0; i < shoppingCart.length; i += 1) {
var totalPriceOf = shoppingCart[i].price;
var myTotal = 0;
for(var i = 0, len = totalPriceOf.length; i < len; i++) {
myTotal += totalPriceOf.price;
}
console.log(myTotal);
}
}
addToCart ('beer', 5);
totalPriceCheck();
I can't understand your question properly but I think you need output like this.
I am doing some changes in your code, please refer below code
output of below code is :- 15
if you add addToCart('beer', 5); than out put will be 20
var shoppingCart = [];
function addToCart(name, price) {
var object = {};
object.name = name;
object.price = price;
shoppingCart.push(object);
}
addToCart('beer', 5);
addToCart('beer', 5);
addToCart('beer', 5);
function totalPriceCheck() {
var myTotal = 0;
for (var i = 0; i < shoppingCart.length; i += 1) {
var totalPriceOf = shoppingCart[i].price;
myTotal += totalPriceOf;
}
console.log(myTotal);
}
totalPriceCheck();
You can use reduce to get the sum :
function totalPriceCheck(){
return shoppingCart.reduce(
(acc, elem)=>acc + elem.price,
0
);
}

Remove current node in an array onclick

I'm working on an ordering application that needs to allow for the user to remove a previously entered order. The 'Remove' button currently removes all output from the screen, and when a new order is added, all past orders and the new order reappear, rather than the single new order.
// Global Variables
var orderTotal = 0;
var grandTotal = 0;
var burritos = [];
function init() {
var btnAddToOrder = document.getElementById("addToOrder");
btnAddToOrder.onclick = processOrder;
}
function processOrder() {
var fieldBurrito = document.getElementById("burrito");
var index = fieldBurrito.selectedIndex;
var burritoChoice = fieldBurrito.options[index].value;
var fieldRice = document.getElementsByName("rice");
for (var a = 0; a < fieldRice.length; a++) {
if (fieldRice[a].checked) {
var riceChoice = fieldRice[a].value;
} else {
riceChoice = "No";
}
}
var fieldBeans = document.getElementsByName("beans");
for (var e = 0; e < fieldBeans.length; e++) {
if (fieldBeans[e].checked) {
var beansChoice = fieldBeans[e].value;
} else {
beansChoice = "No";
}
}
var fieldSalsa = document.getElementsByName("salsa");
var salsaChoice = "";
for (var i = 0; i < fieldSalsa.length; i++) {
if (fieldSalsa[i].checked) {
salsaChoice += fieldSalsa[i].value + " ";
}
}
var fieldGuac = document.getElementsByName("guacamole");
for (var o = 0; o < fieldGuac.length; o++) {
if (fieldGuac[o].checked) {
var guacChoice = fieldGuac[o].value;
} else {
guacChoice = "No Guac";
}
}
//Reset the cost of each individual order
orderTotal = 0;
grandTotal = 0;
//Determine the type of burrito and associate correct cost
switch (burritoChoice) {
case "Chicken":
orderTotal += 6.20;
break;
case "Steak":
orderTotal += 6.75;
break;
case "Carnitas":
orderTotal += 6.60;
break;
case "Sofritas":
orderTotal += 6.20;
break;
case "Barbacoa":
orderTotal += 6.60;
break;
}
if (guacChoice == "Guacamole") {
orderTotal += 1.40;
}
var burritoInstance = {
"Burrito":burritoChoice,
"Rice":riceChoice,
"Beans":beansChoice,
"Salsa":salsaChoice,
"Guacamole":guacChoice,
"Price":orderTotal
};
burritos.push(burritoInstance);
// Check to see that the fieldValues array has at least one element
if (burritoChoice !== "Choose a Burrito") {
generateReceipt(burritos);
} else {
console.log("Please choose a burrito type to continue. All other toppings are optional.");
}
}
//********************************************************************************************
function removeButton(i) {
var removeButton = document.createElement("button");
var value = document.createTextNode("Remove Order");
removeButton.appendChild(value);
removeButton.id = i;
removeButton.onclick = function() {
var thing = this.parentNode;
thing.parentNode.removeChild(thing);
}
return removeButton;
}
//--------------------------------------------------------------------------------------------
function br() {
return document.createElement('br');
}
//********************************************************************************************
function generateReceipt(burritos) {
var element = document.getElementById("output");
if(element) {
element.parentNode.removeChild(element);
}
var burritoList = document.createElement("div");
burritoList.id = "output";
for(var i=0; i < burritos.length; i++) {
var outputList = document.createTextNode(burritos[i].Burrito + " Burrito - " +
burritos[i].Rice + " Rice - " +
burritos[i].Beans + " Beans - " +
burritos[i].Salsa + " Salsa - " +
burritos[i].Guacamole + " - $" +
burritos[i].Price);
outputList.id = "burritoInstance";
grandTotal += burritos[i].Price;
burritoList.appendChild(outputList);
burritoList.appendChild(removeButton(i));
burritoList.appendChild(br());
}
var orderTotal = document.createTextNode("Order Total: $" + grandTotal);
burritoList.appendChild(orderTotal);
document.body.appendChild(burritoList);
}
At some point I will need to include logic in the button click to adjust the order total when an order is removed, but first I need to be able to access the order preceding each button.
JSFiddle

Categories

Resources