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

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
);
}

Related

problem using .split() method in a function but it works on console.log

the problem is only in the bottom function objectPutter
specifically the line with wowza.split(' '); labelled with the comment
let eq
let x = null
let bracketNum = 0
let k = 0
let pre = 0
class subEqCreator { //subEq object
constructor() {
this.precede = 0;
this.text = '';
}
parser() {
this.text += eq[k]
}
ma() {
this.text.split(' ')
}
};
function trigger() { //used for HTML onClick method
show();
brackets();
subEqDynamic()
parseEquation();
objectPutter()
};
function show() {
const recent = document.querySelector("ol");
const txt = document.getElementById('input');
eq = txt.value;
li = document.createElement('li');
li.innerText = eq;
recent.appendChild(li);
txt.value = '';
};
function brackets() { //counts how many brackets appear
for (let i = 0; i < eq.length; i++) {
if (eq[i] == "(") {
bracketNum++;
};
};
};
let subEqDynamic = function() { // creates a new object for each bracket
for (let count = 0; count <= bracketNum; count++) {
this['subEq' + count] = x = new subEqCreator()
};
};
function parseEquation() { // assign characters to SubEq object
let nextIndex = 0;
let currentIndex = 0;
let lastIndex = [0];
let eqLen = eq.length;
let nex = this['subEq' + nextIndex]
for (k; k < eqLen; k++) {
if (eq[k] == "(") {
nextIndex++;
pre++
this['subEq' + currentIndex].text += '( )';
this['subEq' + nextIndex].precede = pre;
lastIndex.push(currentIndex);
currentIndex = nextIndex;
} else if (eq[k] == ")") {
pre--
currentIndex = lastIndex.pop();
} else {
this['subEq' + currentIndex].parser()
}
}
}
function objectPutter() {
for (let i = 0; i < bracketNum; i++) {
let wowza = this['subEq' + i].text
wowza.split(' '); // 🚩 why isnt it working here
console.log(subEq0);
for (let j = 1; j <= wowza.length; j += 2) { // for loop generates only odds
let ni = i++
wowza.splice(j, 0, this['subEq' + ni])
console.log(i)
}
}
}
to fix this i tried;
making a method for it ma() in the constructor.
putting in the function parseEquation above in case it was a scope issue.
also, i noticed subEq0.split(' ') worked in browser console even replicating it to the way i done it using this['subEq' + i].text.split(' ') where i = 0.
After it runs the it says .splice is not a function and console.log(subEq0) shows subEq0.text is still a string
.split() does not change the variable it returns the splitted variable

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/

How to create n different arrays with 6 random numbers each. - Javascript/Jquery

I want to create 1 - 12 arrays of 6 random numbers each.
At the moment I can only create one. So I don't know how to loop this.
This is my code so far:
<script type="text/javascript">
function schleife() {
var arr = [];
var krams = [];
for(i=1; i<=6; i++) {
var zufall = Math.floor((Math.random() * 49) + 1);
krams.push(zufall++);
}
arr.push(krams.toString() + "<br /><br />");
$(".bsp2").append(arr);
}
function uebertrag() {
schleife();
}
</script>
You need to create new function: e.g. getArrayOfRandomNumbers
function getArrayOfRandomNumbers() {
var krams = []
for(var i=1; i<=6; i++) {
var zufall = Math.floor((Math.random() * 49) + 1)
krams.push(zufall++)
}
return krams
}
And now you can invoke this function in loop:
for (var j = 0; j < 12; j++) {
var arrayOfRandomNumber = getArrayOfRandomNumbers()
//do something with this array, e.g. append
$(".bsp2").append(arrayOfRandomNumber.toString())
}
function schleife(iRange, jRange) {
var array = []
for (i = 1; i <= iRange; i++) {
var krams = [];
for(j = 1; j <= jRange; j++) {
var zufall = Math.floor((Math.random() * 49) + 1);
krams.push(zufall++);
}
array.push(krams);
$(".bsp2").append(krams + "<br /><br />");
}
return array;
}
schleife(12, 6);
Thank you havenchyk. I was able to make it with your code!
Great! I'm really happy up to this point. ;-)
That's how it looks now:
function getArrayOfRandomNumbers() {
var krams = [];
while(krams.length < 6) {
var zufall = Math.floor((Math.random() * 49) + 1);
var found = false;
for(var i=0; i<krams.length; i++) {
if(krams[i] == zufall) {
found = true;
break
}
}
if(!found){
krams.push(zufall++);
}
}
return krams;
}
function getArrays() {
function compareNumbers(a, b) {
return a - b;
}
var results = [];
for (var j = 0; j <= 10; j++) {
var arrayOfRandomNumber = getArrayOfRandomNumbers();
//do something with this array
results.push(arrayOfRandomNumber.splice(0, 6).sort(compareNumbers).toString()+"<br /><br />");
}
$(".bsp2").append(results[1]);
$(".bsp2").append(results[2]);
$(".bsp2").append(results[3]);
$(".bsp2").append(results[4]);
$(".bsp2").append(results[5]);
$(".bsp2").append(results[6]);
$(".bsp2").append(results[7]);
$(".bsp2").append(results[8]);
$(".bsp2").append(results[9]);
$(".bsp2").append(results[10]);
}

JavaScript updating last index class data

I have following issue.
I have array of objects, and when I want to get one of the items and update data, it updates last data.
for example:
var arr = [];
for (var i = 0; i < 8; i++){
var c = new MyClass1(i);
arr.push (c)
}
and the MyClass1
(function () {
var score = 0;
function MyClass1(id){
this.id = id;
this.x = 100;
//some code. not important
}
var p = MyClass1.prototype;
p.updateScore = function (s){
score = s;
}
window.MyClass1 = MyClass1;
}());
and function which returns one of these classes
var getMyClassesById = function(/* int */ id){
var size = arr.length;
for (var i = 0; i<size; i++){
if (id == arr[i].id){
return arr [i];
}
}
}
Finally I'm calling function and want to update Score
getMyClassesById(1).updateScore (122);
it's updates last index item Score, and calls last item "updateScore" function... why?
but when i'm changing some other property its changes correctly for example "x". I can't understand is here something not right with prototypes?
Your variable score is not defined as a member of MyClass - it is only defined in the scope of your closure. Your code will work, but there will only be 1 "score" for all instances of MyClass.
If score is supposed to be part of MyClass then move it
function MyClass1(id){
this.id = id;
this.x = 100;
this.score = 0
//some code. not important
}
And update the method:
var p = MyClass1.prototype;
p.updateScore = function (s){
this.score = s;
}
(function () {
function MyClass1(id){
this.id = id;
this.x = 100;
this.score = 0;
//some code. not important
}
var p = MyClass1.prototype;
p.updateScore = function (s){
this.score = s;
}
window.MyClass1 = MyClass1;
}());
var arr = [];
for (var i = 0; i < 8; i++){
var c = new MyClass1(i);
arr.push (c)
}
var getMyClassesById = function(/* int */ id){
var size = arr.length;
for (var i = 0; i<size; i++){
if (id == arr[i].id){
return arr [i];
}
}
}
getMyClassesById(1).updateScore (122);
console.log(arr);

Protractor:How to store values in array and then to do sorting

I need to sort list strings under the table ,so for that i have written following lines of code but on console i am not getting any values:
var j = 9;
var rows = element.all(by.repeater('row in renderedRows'));
var column = element.all(by.repeater('col in renderedColumns'));
expect(rows.count()).toEqual(5); //here its printing number of rows
expect(column.count()).toEqual(5); //here its printing number of columns
var arr = [rows.count()];
for (var i = 0; i < rows.count(); i++) {
console.log("aai" + i);
if (i = 0) {
//var columnvalue=column.get(9).getText();
var columnvalue = column.get(9).getText().then(function(ss) {
return ss.trim();
arr[i] = ss.trim(); //here it will save the value first value of column
console.log("value1" + arr[i]);
expect(arr[i]).toEqual('DN');
console.log("aa" + ss.trim());
});
} else {
var j = j + 8;
var columnvalue = column.get(j).getText().then(function(ss) {
return ss.trim();
arr[i] = ss.trim(); //here it will save the other values of column
console.log("value" + arr[i]);
expect(arr[i]).toEqual('DN');
console.log("ab" + ss.trim());
});
}
}
Sorting_Under_Table: function(col){
test = [];
var m;
var dm = 0;
element(by.xpath('//div[#class="ngHeaderScroller"]/div['+col+']')).click();
element.all(by.repeater('row in renderedRows')).then(function(row) {
m = row.length;
for (i = 1; i <= row.length; i++)
{
user_admin_table_name = browser.driver.findElement(by.xpath('//div[#class="ngCanvas"]/div['+i+']/div['+col+']'));
user_admin_table_name.getText().then(function(text) {
var test_var1 = text.toLowerCase().trim();
test.push(test_var1);
var k = test.length
if (k == m){
for (j = 0; j < test.length; j++){
test.sort();
d=j+1;
user_admin_table_name1 = browser.driver.findElement(by.xpath('//div[#class="ngCanvas"]/div['+d+']/div['+col+']'));
user_admin_table_name1.getText().then(function(text1) {
var test_var2 = text1.toLowerCase().trim();
if (test_var2 == test[dm]){
expect(test_var2).toEqual(test[dm]);
dm = dm +1;
}else {
expect(test_var2).toEqual(test[dm]);
log.error("Sorting is not successful");
dm = dm +1;
}
});
}
}
});
}
});
},
You can use this code for sorting and verifying is it sorted or not
I'm not sure how your above example is doing any sorting, but here's a general solution for trimming and then sorting:
var elementsWithTextToSort = element.all(by.xyz...);
elementsWithTextToSort.map(function(elem) {
return elem.getText().then(function(text) {
return text.trim();
});
}).then(function(trimmedTexts) {
return trimmedTexts.sort();
}).then(function(sortedTrimmedTexts) {
//do something with the sorted trimmed texts
});

Categories

Resources