Looping through objects within an array, taking total of integer values - javascript

I am trying to loop through objects within an array, adding all values with the key 'price'.
var basket = [
{
price: "25.00",
id: "Hat"
}, {
price: "50.00",
id: "Jacket"
}
]
/*objects within array. purpose = able to use a for loop using .length as follows*/
function test() {
for(var i = 0; i < basket.length; i++){
totalPrice = 0;
alert(itemPrice);
itemNum = basket[i];
itemPrice = parseFloat(itemNum.price);
totalPrice += itemPrice;
}
alert(totalPrice);
}
My itemPrice alert shows that the loop runs through both objects, flashing 25 then 50. Why is my totalPrice variable only storing the second price, 50? The operator += should be the same as totalPrice = totalPrice + itemPrice? Any explanation as well as fixes would be very much appreciated, trying to get a good understanding!

The first time you enter the loop, you set totalPrice to 0. Then you add the first item price, so totalPrice is 25. Then you enter the loop for the second time, set totalPrice to 0 again, 0 + 50 = 50.
You should initialize totalPrice before the loop.

use reduce:
basket.reduce( function( previousValue, currentValue ){
return previousValue += parseInt(currentValue.price)
}, 0);
example: http://jsfiddle.net/ysJS8/
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/Reduce

Related

free shipping ... if shopping chart total is greater than $35 ... user input unless total is more $35 in JavaScript

I m not sure what i m doing wrong. Thanks in advance for helping me in this matter.
var sum = 0;
var pricecheck = 35;
while (sum < pricecheck) {
var userinput = prompt("Please enter the cost of the item...");
var num1 = parseInt(userinput);
submitprice.push(num1);
for (i = 0; i < submitprice.length; i++) {
sum += submitprice[i];
}
}
alert("free shipping.");
Declare sum to zero each time you are executing the sum of items. Or else it will keep on adding to the sum that was calculated in previous iteration.
Also your submitprice seems to be undefined. I have initilaized it as an empty array.
Working Fiddle
var sum = 0;
var pricecheck = 35;
const submitprice = [];
while (sum < pricecheck) {
var userinput = prompt("Please enter the cost of the item...");
var num1 = parseInt(userinput);
submitprice.push(num1);
sum = 0;
for (i = 0; i < submitprice.length; i++) {
sum += submitprice[i];
}
}
alert("free shipping.");
To start, you need to create an empty array to store the totals in. For this, I will call it "cart":
var cart = [];
Next, I would suggest creating an if statement to check if the input is a number:
var num1 = parseInt(userinput);
if(isNaN(userinput){
alert("Please enter a number");
continue;
}
You don't need the for loop to add the input to the sum, just remove the loop:
sum += userinput
After the loop, you would push to the cart:
cart.push(num1)
Finally, you need to check if the sum is more than free shipping
if(sum >= pricecheck) {
alert("You qualify for free shipping!")'
}
Then just output the result to the console with a pipe (|) concatenated between the numbers.
console.log(cart.join(" | ")
var sum = 0;
var cart = [];
var pricecheck = 35;
while (sum < pricecheck) {
var userinput = prompt("Please enter the cost of the item...");
if (userinput === null) {
break;
}
var num1 = parseInt(userinput);
if (isNaN(userinput)) {
alert("Please enter a number");
continue;
}
cart.push(num1);
sum += num1;
}
if (sum >= pricecheck) {
alert("free shipping.");
}
I took a look at this assignment again to refresh on what was asked for this question. You do not need to have that for loop at all within the while loop. Within each iteration of the while loop, you are asking the user for the price of their next item, adding it to the shopping cart, and also adding it to a running total (this total being your "sum"). This running total does not need to be re-calculated each time inside of the while loop because you would have done that in a single line. You are trying to calculate the price, starting at 0, each time you loop through the while loop (using your for loop). But this is not needed as you already have a running total that can be added to each time the user enters a value.
"Austin Caron" explained it well but for this assignment we do not need to do user authentication.
P.S. Try your best to avoid asking questions directly about an assignment and ask more general questions about a concept or idea you are struggling with.

Accessing Individual Items in an Array and Adding Them to a Total Variable

I am super new to Javascript and currently a student in a bootcamp and am completely stuck on this question...
"Using the shoppingCart variable, create a function that takes the shoppingCart variable and returns the total cost of both items as the total variable."
The code I am given is:
var shoppingCart = [20, 15];
function getTotalCost(prices){
let total = 0;
// code below
// code above
return total;
}
getTotalCost(shoppingCart);
I know that I have to complete the function and loop through the array in shoppingCart but I am having a lot of trouble figuring out how to add the array numbers so that it comes out as the total.. I would REALLY appreciate any help. Thank you!
You can easily achieve it by for loop in javascript, similar to
var shoppingCart = [20, 15];
function getTotalCost(shoppingCart){
let total = 0;
for(var i in shoppingCart) { total += shoppingCart[i]; }
return total;
}
console.log(getTotalCost(shoppingCart));
You can just iterate your array of prices with the forEach function.
var shoppingCart = [20, 15];
function getTotalCost(prices){
let total = 0;
// forEach works with arrays.
prices.forEach(function(price){
// Parse your value into an integer to prevent string concatenations.
total = total + parseInt(price);
});
return total;
}
let total = getTotalCost(shoppingCart);
console.log('Your shopping cart total is:', total);
var shoppingCart = [20, 15];
function getTotalCost(prices){
let total = 0;
// Loop through each element of the array 'prices'
for (var i = 0; i < prices.length; i++){
// Add individual item to total sum
total += prices[i];
}
return total;
}
console.log(getTotalCost(shoppingCart));

Add multiple numbers to Array

I have two arrays. They look like this:
array price = 14.60, 39.00
and
array quantity = 10, 5
(quantity is the quantity of items the user want to buy - 10 items from productA and 5 of productB)
Now I want loop through the variables to multiply the price with the quantity.
Like :
14,60 * 10
and
39,00 * 5
and add the two results to the endPrice variable.
I get the quantity array like this:
$('.quantity').change(function () {
quantitys = $('input[type=number]').map(function () {
return $(this).val();
}).get();
});
and the different prices like this:
var prices = $('.priceCell').map(function () {
return parseFloat($(this).html().trim());
}).get();
And that's what I tried:
var endPrice = 0;
for (var q = 0; q < quantitys.length; q++) {
for (var p = 0; p < prices.length; p++) {
endPrice = quantitys[q] * prices[p];
}
}
alert(endPrice);
Well, that haven't worked for me so well. Can someone help me there? Doesn't matter if the solution is pure JavaScript or jQuery.
You are using two loops while you should only use one. Also, add to endPrice by using +=:
var endPrice = 0;
for (var q = 0; q < quantitys.length; q++) {
endPrice += parseFloat(quantitys[q]) * parseFloat(prices[q]);
}
alert(endPrice);
1st problem
You were using nested loops thus every quantity would be multiplied by every prices. You only need one loop.
2nd problem
You were using endPrice = .... This will override the endPrice every time you go through this line. You need to use += that will add to the current enbPrice
var prices = [14.60, 39.00];
var quantities = [10,5];
var endPrice = 0;
for(let i=0, l=prices.length;i<l;i++){
endPrice += prices[i] * quantities[i];
}
console.log(endPrice);
EDIT
OP need to have separated totals. (See #David Thomas's answer)
You can use Array.prototype.map()
var prices = [14.60, 39.00];
var quantities = [10, 5];
var totals = prices.map((p, index) => p * quantities[index]);
console.log(totals);
You can't use the double loop for this. This multiplies every price with every quantity. What you want to do is this:
var endPrice = 0;
for (var i = 0; i < quantitys.length; i++) {
endPrice += quantitys[i] * prices[i];
}
To multiply every price in one Array by the number held at the same index in a second Array I'd recommend:
var price = [14.60, 39.00],
quantity = [10, 5],
// here we iterate over the price Array, using
// Array.prototype.map() in order to return a
// new Array:
totals = price.map(
// p: the current array-element of
// the Array of prices,
// index: the index of the current
// array-element of the Array.
// using an Arrow function to
// multiply the price ('p') by
// the value held in the quantity
// Array at the same index:
(p,index) => p * quantity[index]
);
// logging the created 'totals' Array to the console:
console.log(totals); // [146,195]
// logging the created Array, after joining its
// elements together to form a String with values
// separated with a ',' character:
console.log(totals.join(',')); // "146,195"
Close, you're missing += instead of =
endPrice += quantitys[q] * prices[p];
Dependent on your values, you may also want to parse them, so:
endPrice += (parseInt(quantitys[q]) * prices[p]) // you're already parsing prices;
Edit with more information in comments:
Because of the way your code is, they prices are on the same row as the quantities, so they'll be the same. So, the new code will be...
for (var q = 0; q < quantitys.length; q++) {
endPrice += parseInt(quantitys[q]) * prices[q];
}
const prices = [14.60, 39.00];
const qty = [10, 5];
const endPrice = prices.reduce((total, price, i) => total + price * qty[i], 0);
console.log(endPrice);

Accessing indexes of a string inside an array and taking the sum

Ok so I am trying to access each individual number in the strings inside of this array.
var array = ['818-625-9945','999-992-1313','888-222-2222','999-123-1245'];
var str = "";
for (i=0; i<array.length; i++) {
str = array[i];
}
The problem is that this is the output: '999-992-1313'
and not the first element array[0]: '818-625-9945'
When I try doing a nested for loop to go through each element inside the string I am having trouble stating those elements.
var array = ['818-625-9945','999-992-1313','888-222-2222','999-123-1245'];
for (i=0; i<array.length; i++) {
for (j=0; j<array[i].length; j++) {
console.log(array[i][j]);
}
}
I do not know how to access each individual number inside of the string array[i]. I would like to find a way to make a counter such that if I encounter the number '8' I add 8 to the total score, so I can take the sum of each individual string element and see which number has the highest sum.
var array = ['818-625-9945','999-992-1313','888-222-2222','999-123-1245'];
for (i=0; i<array.length; i++) {
for (j=0; j<array[i].length; j++) {
if (array[i](j).indexOf('8') !== -1) {
// add one to total score
// then find a way to increase the index to the next index (might need help here also please)
}
}
}
Mabe this works for you. It utilized Array.prototype.reduce(), Array.prototype.map() and String.prototype.split().
This proposal literates through the given array and splits every string and then filter the gotten array with a check for '8'. The returned array is taken as count and added to the return value from the former iteration of reduce - and returned.
var array = ['818-625-9945', '999-992-1313', '888-222-2222', '999-123-1245'],
score = array.reduce(function (r, a) {
return r + a.split('').filter(function (b) { return b === '8'; }).length;
}, 0);
document.write('Score: ' + score);
A suggested approach with counting all '8' on every string:
var array = ['818-625-9945', '999-992-1313', '888-222-2222', '999-123-1245'],
score = array.map(function (a) {
return a.split('').filter(function (b) { return b === '8'; }).length;
});
document.write('Score: ' + score);
Actually rereading your question gave me a better idea of what you want. You simply want to count and retrieve the number of 8's per string and which index in your array conforms with this maximum 8 value. This function retrieves the index where the value was found in the array, how many times 8 was found and what is the string value for this result. (or returns an empty object in case you give in an empty array)
This you could easily do with:
'use strict';
var array = ['818-625-9945', '999-992-1313', '888-222-2222', '999-123-1245'];
function getHighestEightCountFromArray(arr) {
var max = 0,
result = {};
if (arr && arr.forEach) {
arr.forEach(function(value, idx) {
var cnt = value.split('8').length;
if (max < cnt) {
// found more nr 8 in this section (nl: cnt - 1)
max = cnt;
// store the value that gave this max
result = {
count: cnt - 1,
value: value,
index: idx
};
}
});
}
return result;
}
console.log(getHighestEightCountFromArray(array));
The only thing here is that when an equal amount of counts is found, it will still use the first one found, here you could decide which "maximum"
should be preferred(first one in the array, or the newest / latest one in the array)
OLD
I'm not sure which sums you are missing, but you could do it in the following way.
There I first loop over all the items in the array, then I use the String.prototype.split function to split the single array items into an array which would then contain ['818', '625', '9945']. Then for each value you can repeat the same style, nl: Split the value you are receiving and then loop over all single values. Those then get convert to a number by using Number.parseInt an then all the values are counted together.
There are definitelly shorter ways, but this is a way how you could do it
'use strict';
var array = ['818-625-9945','999-992-1313','888-222-2222','999-123-1245'],
sumPerIndex = [],
totalSum = 0;
array.forEach(function(item, idx) {
var values = item.split('-'), subArray = [], itemSum = 0;
values.forEach(function(value) {
var singleItems = value.split(''),
charSum = 0;
singleItems.forEach(function(char) {
charSum += parseInt(char);
});
itemSum += charSum;
subArray.push(charSum);
console.log('Sum for chars of ' + value + ' = ' + charSum);
});
sumPerIndex.push(subArray);
totalSum += itemSum;
console.log('Sum for single values of ' + item + ' = ' + itemSum);
});
console.log('Total sum of all elements: ' + totalSum);
console.log('All invidual sums', sumPerIndex);

Using javascript to take the lowest two numbers from the total of a table row

I am attempting to write a page which has a table where the user can input a number in each cell, it would then display a total of that row with the lowest two values of that row subtracted. The code creates the array, finds the total of the array and the lowest 2 values (low and low2 in the code below). However when I try to take the two lowest values from the total, i get an error. I think i have found the error as testing the values using isNaN i find that the sum of the array is not a number, which doesn't seem to make sense to me. Here is where I got up to with the code:
table = document.getElementsByTagName("tbody")[0];
allrows = table.getElementsByTagName("tr");
for (i=0; i < allrows.length; i++) {
rowTotal = 0;
rowArray =[];
for (ii=0; ii < allrows[i].getElementsByTagName("input").length; ii++) {
rowTotal = rowTotal + Number(allrows[i].getElementsByTagName("input")[ii].value);
rowArray.push(Number(allrows[i].getElementsByTagName("input")[ii].value));
var tots=rowTotal;
}
rowArray.sort(function(a, b){return b-a});
var low = $(rowArray[rowArray.length-2]);
var low2 = $(rowArray[rowArray.length-1]);
rowTotaladj = rowTotal- low - low2;
$(".row-total:eq("+(i-1)+")").html(rowTotaladj);
}
Here is a link to a previous version of the page which correctly displays the total (rowTotal) but does not have the total minus the lowest two values in:
Any explaination as to why the sum is not a number and help with the code would be much appreciated.
Since you're already using jQuery, you can use the following code to achieve what you want:
// When an <input> is changed:
$('table input').on('change', function() {
var sum = 0,
vals = [ ];
$(this).parents('table').find('input').each(function() {
var val = parseInt( $(this).val() ) || 0;
vals.push( val );
sum+= val;
});
// Now sort the array:
vals.sort();
total = sum - vals[0] - vals[1];
$('tfoot td').html( total );
});
jsFiddle Demo

Categories