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);
Related
I am trying to display up to three recipes from an API that specifically include bacon as an ingredient. The API only has 10 recipes that meet this criteria, so I am running into an issue where the same recipes are sometimes being repeated on the page if the user wishes to view two or three recipes. How can I set a condition to check if the random number that I am generating and storing in an array is a duplicate value? If a duplicate, then I want for the iterator to be subtracted by 1 and the for loop to continue. I've listed the code I've I appreciate any feedback that is provided!
// The number of recipes the user would like to display//
var recipeNumber = $("#recipe-input").val();
var parsedInput = parseInt(recipeNumber);
// creating an empty array that will story the random numbers that are generated//
var ranNumArr = [];
console.log(ranNumArr);
for (i = 0; i < parsedInput; i++) {
// generate a random number based on the length of the recipe API's array of bacon recipes (10) and push it into the ranNumArr//
var randomNumber = Math.floor(Math.random() * 10);
ranNumArr.push(randomNumber);
// If the value of the index in the array is equal to a previous index's value, repeat the iteration//
if (ranNumArr[i] === ranNumArr[i -1] || ranNumArr[i] === ranNumArr[i -2]){
console.log("this is a duplicate number")
i = i - 1
}
// else, display the recipe on the card//
else {
randomRecipe = ranNumArr[i]
// Create cards that will house the recipes//
var recipeCell = $("<div>").attr("class", "cell");
$("#recipes-here").append(recipeCell);
var recipeCard = $("<div>").attr("class", "card");
recipeCell.append(recipeCard);
var recipeSection = $("<div>").attr("class", "card-section");
recipeCard.append(recipeSection);
var cardTitleE1 = $("<h1>");
cardTitleE1.attr("id", "recipe-title");
var cardImageE1 = $("<img>");
cardImageE1.attr("id", "recipe-image");
var cardTextE1 = $("<a>");
cardTextE1.attr("id", "recipe-link");
// Adding the recipe title, url, and image from the API call//
cardTitleE1.text(response.hits[randomRecipe].recipe.label);
cardTextE1.text("Click here for link to recipe");
cardTextE1.attr("href", response.hits[randomRecipe].recipe.url);
cardTextE1.attr("target", "_blank");
cardImageE1.attr("src", response.hits[randomRecipe].recipe.image);
// Display the recipe on the DOM//
recipeSection.append(cardTitleE1);
recipeSection.append(cardImageE1);
recipeSection.append(cardTextE1);
}
}
You can use a Set to store numbers that have already been chosen.
const set = new Set;
//....
if (set.has(randomNumber)){
console.log("this is a duplicate number");
i--;
} else {
set.add(randomNumber);
//...
Alternatively, as Barmar suggested, you can shuffle the array of integers from 0 to 9 beforehand and then loop over the values for better efficiency. Below I have provided an example using the Fisher-Yates shuffle.
const arr = [...Array(10).keys()];
for (let i = arr.length - 1; i > 0; i--) {
const j = Math.random() * (i + 1) | 0;
const temp = array[i];
array[i] = array[j];
array[j] = temp;
}
for(const num of arr){
//do something with num...
}
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));
I have an array of input fields called '$inputFieldsArray' then I slice them to group by 3 into 'newArray' then I need new array value for each item to assign to another array cause in the end I need an array with input fields values grouped by 3. The end goal is to get an array which contains for 9 input fields ex [[i1,i2,i3],[i4,i5,i6],[i7,i8,i9]].
For some reason 'stringArray' output is nothing, first two arrays print correct results. It's probably some mistake I do regarding JS arrays.. Sorry js is not my main language, I try to learn it. Thanks.
Here is a screenshoot with chrome console:
Here is my function:
$($submitButton).click(function () {
// Get number of input fields
let $total = $("input[name^='bodyHeader']").length;
// Get input fields as objects
let $inputFieldsArray = $("input[name^='bodyHeader']");
let newArray = [];
let stringArray = [];
let j = 0;
// Group input fields by 3
for (let i = 0; i < $total - 1; i += 3) {
newArray[j] = $inputFieldsArray.slice(i, i + 3);
j++;
}
// Extract string values from newArray and pass them into stringArray
for (let k = 0; k < newArray.length - 1; k++) {
stringArray[k][0] = newArray[k][0].value;
stringArray[k][1] = newArray[k][1].value;
stringArray[k][2] = newArray[k][2].value;
}
// Print to test results
console.log($inputFieldsArray);
console.log(newArray);
console.log("String Array: " + stringArray);
... // Function logic is not complete
});
SOLUTION:
There is no way to declare dynamic length bidimensional array in js. Use this approach suggested by #Stephan :
stringArray[k] = [newArray[k][0].value, newArray[k][1].value,
newArray[k[2].value];
or this approach suggested by #Lorenzo Gangi:
var matrix = [],
cols = 3;
//init the grid matrix
for ( var i = 0; i < cols; i++ ) {
matrix[i] = [];
}
stringArray[k] is undefined because you defined stringArray as [] (Your browser probably threw an exception). Additionally newArray[k] starts at index 0.
You could write stringArray[k] = [newArray[k][0].value, newArray[k][1].value, newArray[k][2].value] instead.
Basically,
stringArray[k]
is undefined yet, therefore setting its [0] property wont work. May do:
stringArray[k] =newArray[k].map(el=>el.value);
Alltogether:
$($submitButton).click(function () {
let stringArray = $("input[name^='bodyHeader']").toArray().reduce((res,_,i,arr)=>((i%3==0 && res.push(arr.slice(i,i+3).map(e=>e.value))),res),[]);
});
I'm trying to sum and then average a stream of data, some code here.
var getAverage = function(dataArray){
var total,
sample = dataArray.length,
eArray = Array.prototype.slice.call(dataArray);
for (var i = 0; i< sample; i++) {
total+= eArray[i];
}
return total;
}
var output = function(){
//source data
var dataArray = new Uint8Array(bufferLength);
analyser.getByteTimeDomainData(dataArray);
var average = getAverage(dataArray);
$('#average').text(average);
window.requestAnimationFrame(output);
Every element in the array returns a number, but it still returns NaN. Help?
Set total = 0; currently it is defaulting to undefined. undefined + a number = NaN, and NaN + a number = NaN.
The declared variable total is undefined which means it will create NaN (Not-a-Number) when a number is added to it.
Also, Typed Array (ArrayBuffer/views) and Array are not the same, and converting a typed array to an ordinary Array is making iteration slower as typed arrays are actual byte-buffers while Arrays are (node) lists. That on top of the cost of conversion itself.
Just add them straight forward. Remember to divide the sum on length and of course to initialize total:
var getAverage = function(dataArray){
var total = 0, // initialize to 0
i = 0, length = dataArray.length;
while(i < length) total += dataArray[i++]; // add all
return length ? total / length : 0; // divide (when length !== 0)
}
How can you, in using a random number generator, stop a number from appearing if it has already appeared once?
Here is the current code:
var random = Math.ceil(Math.random() * 24);
But the numbers appear more than once.
You can use an array of possible values ( I think in your case it will be 24 ) :
var values = [];
for (var i = 1; i <= 24; ++i){
values.push(i);
}
When you want to pick a random number you just do:
var random = values.splice(Math.random()*values.length,1)[0];
If you know how many numbers you want then it's easy, first create an array:
var arr = [];
for (var i = 0; i <= 24; i++) arr.push(i);
Then you can shuffle it with this little function:
function shuffle(arr) {
return arr.map(function(val, i) {
return [Math.random(), i];
}).sort().map(function(val) {
return val[1];
});
}
And use it like so:
console.log(shuffle(arr)); //=> [2,10,15..] random array from 0 to 24
You can always use an hashtable and before using the new number, check if it is in there or not. That would work for bigger numbers. Now for 24, you can always shuffle an array.
You could put the numbers you generate in an array and then check against that. If the value is found, try again:
var RandomNumber = (function()
{
// Store used numbers here.
var _used = [];
return {
get: function()
{
var random = Math.ceil(Math.random() * 24);
for(var i = 0; i < _used.length; i++)
{
if(_used[i] === random)
{
// Do something here to prevent stack overflow occuring.
// For example, you could just reset the _used list when you
// hit a length of 24, or return something representing that.
return this.get();
}
}
_used.push(random);
return random;
}
}
})();
You can test being able to get all unique values like so:
for(var i = 0; i < 24; i++)
{
console.log( RandomNumber.get() );
}
The only issue currently is that you will get a stack overflow error if you try and get a random number more times than the amount of possible numbers you can get (in this case 24).