I am trying to get user input and store it on an array but I can't seem to get the correct output, when I console log the results I get different arrays with 0 length
Here's my code.
let bambooInputElement = document.querySelector('.bambooInputElement');
let bambooTotal = [];
function calculateBamboo() {
bambooInputElement = bambooInputElement.value;
if (bambooInputElement < 25) {
alert('Pledge must be at least $25.');
}else {
let amountDonated = 0;
for (let i = 0; i < bambooTotal.length; i++) {
bambooTotal.push(bambooInputElement);
amountDonated = amountDonated + bambooTotal[i];
}
}
}
bambooBtnElement.addEventListener('click', calculateBamboo);
bambooInputElement is exactly what it says - and that's an Element, not its value - don't reassign types. Use a new variable instead.
Array.prototype.push() should be outside of the loop. Actually you don't need a for loop at all, use Reduce.
Use Array.prototype.reduce() to reduce an array to a single value (the total amount)
Use return inside a function to return a result / or an alert - if that's what you want.
const bambooInputElement = document.querySelector('.bambooInputElement');
const bambooBtnElement = document.querySelector('.bambooBtnElement');
const bambooDonations = []; // this is not total, those are donations!
function calculateBamboo() {
const val = parseFloat(bambooInputElement.value);
if (val < 25) return alert('Pledge must be at least $25.');
// Add to array of donations
bambooDonations.push(val);
// Get total donations
const totalDonations = bambooDonations.reduce((a, v) => a+=v, 0);
// Reset input value
bambooInputElement.value = "";
console.log(totalDonations); // TEST ONLY
// return that total:
return totalDonations;
}
bambooBtnElement.addEventListener('click', calculateBamboo);
<input type="number" class="bambooInputElement">
<button type="button" class="bambooBtnElement">CALCULATE</button>
The line bambooTotal.push(bambooInputElement) should be before the for loop. This is because, without pushing an element in the array, the length will always be zero hence it won't enter in the array.
Putting that line out of the for loop will ensure that the value get's entered and then the array is of atleast length 1.
Related
I am new to JSON, so bear with me!
I am working on a website that stores values to LocalStorage via inputs. Each form input has the following function (only difference is formInput2, formInput3)
function formInput(e) {
// Save userInput from input
// Get form values
var input = document.querySelector('.input').value;
this.style.visibility = 'hidden';
smtBtn.style.display = 'inline-block'
var userInput = {
answer: input
}
// Test if bookmark is null
if (localStorage.getItem('bookmarks') === null) {
// Init Array
var bookmarks = [];
// Add to array
bookmarks.push(userInput);
// Set to LocalStorage
localStorage.setItem('bookmarks', JSON.stringify(bookmarks));
} else {
// Get Bookmarks from LocalStorage
var bookmarks = JSON.parse(localStorage.getItem('bookmarks'));
// Add bookmark to array
bookmarks.push(userInput);
// Reset back to LocalStorage
localStorage.setItem('bookmarks', JSON.stringify(bookmarks));
}
// Refetch bookmarks
fetchBookmarks();
// Prevent form from submitting
e.preventDefault();
}
I need to add the three numbers that are in local storage, and I am using this function:
function bookmarkMath() {
var bm1 = JSON.parse(localStorage.getItem('bookmarks')),
total = 0,
i;
for (i = 0; i < bm1.length; i++) {
total += bm1[i].answers;
}
console.log(total);
}
}
But alas, my output is NaN. :(
Any help would be very appreciated!!!!!!!
edit: In dev tools, this is what I get back with console.log(LocalStorage) - the numbers I have entered in the form on the site.
Storage {bookmarks: "[{"answer":"2"},{"answer":"4"},{"answer":"5"}]", length: 1}
bookmarks: "[{"answer":"2"},{"answer":"4"},{"answer":"5"}]"
length: 1
__proto__: Storage
Edit 2: I have updated the second ]function to include the JSON.parse. But now I am getting just the numbers 0245 as my result, NOT the sum of 0+2+4+5. Any help?? :p
You are on the right track by doing JSON.parse(). However, the value is in a string. You can see quote at the value it is mean will be threated as a string. You should convert it to number format like following:
total += parseInt(bm1[i].answers);
If you don't want to do parseInt() then your output should be :
{"answer": 2} //this one mean your value is Number
Instead:
{"answer":"2"} //this one mean your value is in String
I think I see it ... this statement looks "wrong, yet something that JavaScript would accept!"
var bm1 = JSON.parse(localStorage.getItem('bookmarks')),
total = 0,
i;
Notice the commas.
Instead, write this as three separate lines:
var var bm1 = JSON.parse(localStorage.getItem('bookmarks'));
var total = 0;
var i;
const bookmarks = JSON.parse(localStorage.getItem('bookmarks')) || []
const totalAnswers = bookmarks.map(o => +o.answer).reduce((a, b) => a + b)
This is my array from which I want to find max.
number = {"abc": [43,4,34,34,6,444], "dsfsd":[324,324,32,43,34,2] };
console.log((Math.max(...number[abc]));
Here the output is 444, and it's working fine. But now, I want to select max from selected indexs. I am storing those indexes in this array.
available = [0,2,3];
Now, index 0,2,3 of number[abc] are 43,34, 6
And I want 43 to be displayed, because it is the max from selected indexes.
How can I do it?
Map the indicies to the values, and then call Math.max on those values:
const number = {"abc": [43,4,34,34,6,444], "dsfsd":[324,324,32,43,34,2] };
const available = [0,2,3];
const availableValues = available.map(i => number.abc[i]);
console.log(Math.max(...availableValues));
You can create a reusable function that will have a custom logic to check the highest number instead of using Math.max(). Using reusable function will help you to scale the code without duplicating the logic.
var available = [0,2,3];
var number = {"abc": [43,4,34,34,6,444], "dsfsd":[324,324,32,43,34,2] };
function getHighest(available, number){
var index = available[0];
var highest = number[index];
for(var i=1; i<available.length; i++){
index = available[i];
if(highest < number[index]){
highest = number[index];
}
}
return highest;
}
var highest = getHighest(available, number['abc']);
console.log(highest);
You can also achview this by filtering the number.abc array.
const number = {"abc": [43,4,34,34,6,444], "dsfsd":[324,324,32,43,34,2] };
const available = [0,2,3];
const filtered = number.abc.filter((num, idx) => available.includes(idx));
console.log(Math.max(...filtered));
I'm having trouble solving this question (the result is always undefined) and I am not sure what I'm doing wrong... any ideas?
Write a function that takes a number and generates a list from 0 to that number.
Use the function to assign a value to the myNumberList variable so that it has the value of a list going from 0 to 5.
Assign a value to the variable secondLastItem that should be the second last item of the myNumberList array.
function listMaker(listLength) {}
var myNumberList = null; // replace with number list created by listmaker
var secondLastItem = null; // replace with second last item
You can try the following way using ES6's spread operator (...):
function listMaker(listLength) {
return [...Array(listLength).keys()];
}
var myNumberList = listMaker(10);
// If you want the specified number passed as argument to be included as the last item in the array then push it.
myNumberList.push(10);
console.log(myNumberList);
Here is one way to write it:
function listMaker(number) {
var secondToLast;
var list = [];
for (var i = 0; i <= number; i++){
list.push(i);
}
secondToLast = list[list.length - 2];
return [list, secondToLast]
}
var list = listMaker(5)[0];
var secondToLast = listMaker(5)[1]
console.log(list + "\n" + secondToLast);
That is the snippet ^
Here is the jsfiddle
I am using this function to pass every element in an array to use it in an if statement The problem is that the function is always returning the last value of the array Please help.
function getQtyCheck()
{
var qty;
var id;
var checkQty = new Array()
if(localStorage.getItem("checkout")!=null || localStorage.getItem("checkout")!=""){
checkQty = JSON.parse(localStorage.getItem("checkout"));
for(var t =0; checkQty.length >t; t++){
id = checkQty[t];
t++;
qty = checkQty[t];
}//end for loop
return {ids:id,qtys:qty}
}//end checkout
}
Then in another part of the script I ma using these variables like this
var result = getQtyCheck();
var id = result.ids;
var qty = result.qtys;
if(this.id == id){
var tqty = this.quantity-qty;
Each loop iteration, you assign id and qty to the currently iterated item. Once the loop is over, you return an object with the LAST iterated item set to your variables. Since your return is immediately after the loop and using variables set within the loop, you will always get the last values.
I think I'm following what you are trying to do now. You want to return every element in the array as an array of objects right?
function getQtyCheck() {
var qty,
id,
checkQty = [],
returnValues = [];
if(localStorage.getItem("checkout")!=null && localStorage.getItem("checkout")!=""){
checkQty = JSON.parse(localStorage.getItem("checkout"));
for(var t =0, len = checkQty.length; len > t; t++){
id = checkQty[t];
t++;
qty = checkQty[t];
returnValues.push({ id: id, qty: qty });
}
return returnValues;
}
}
In the loop, build an array of the objects you want to return. After the loop, return the newly created array.
It's returning the last one every time because you're looping it which is adding it up, but then you're using return outside the loop, which is just going to get the last one that it ran.
You shouldn't return inside the for loop because it will try to return multiple times. What you can do though is push it to an array and then get it at the end.
Hi im trying to make a single popup window consisting of only values in the array that are larger/ smaller than a certain number. How can I go about doing this?
<script>
var moe = [3,3.14,4.3,8,9,19,23,24,46,54,87];
var noe = moe.indexOf(23);
function myFunction()
{
alert(noe);
}
function compare(){
for (var i=0;i<moe.length;i++){
if (moe[i]>10){
alert(moe[i]);
}
}
}
</script>
Like so:
function compare(){
var out = [];
for (var i=0;i<moe.length;i++){
if (moe[i]>10){
out.push(moe[i]);
}
}
alert(out.join());
}
Lets walk through the problem:
Given an array of values: values = [3,3.14,4.3,8,9,19,23,24,46,54,87];.
We want to filter the result based on the value being larger than 10.
Finally output the result in an alert dialog box (which takes a string).
Step one is to work out the filtering and then how to turn the result into a string to apps to the alert() function.
(function() {
var i, len, values, value, results, string_value;
values = [3,3.14,4.3,8,9,19,23,24,46,54,87];
results = []; // Empty array which we will build in order during the filter
for (i = 0, len = values.length; i < len; i++) {
value = values[i]; // Not needed; used for readability
if (value > 10) {
results.push(value); // Add this value to the results array
}
}
// Now that we have a result lets convert that to a string
string_value = results.join(", ");
// And output the result with some string concatenation
alert("Filtered results: [ " + string_value + " ]");
// The use of string_value is optional, you could in-line
// this into the alert line
})();