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
Related
I'm using app script
I have Return array from API by this code :
const price= jsonResponce.price.map(obj => [obj[0],obj[1]]);
Give me [[30.56, 1.014], [50.44, 1.019], [10.35, 1.081], [10.34, 1.115], [10.40, 2.006]]
Not this array can be has 1000 array or large
Now I want to sum all object in obj[0] by using this code :
I use to method to see the deference but nothing work
var first= [];
var second= 0;
price.forEach(function(obj){
first+= obj[0];
second+= obj[1];
});
Logger.log(first);
Logger.log(second);
But Give me result like that: first Logger.log(first);
30.5650.4410.3510.3410.40
second Logger.log(second); : this method add number 0 after any obj
01.01401.01901.08101.11502.006
Any idea for this problem
30.56+50.44+10.35+10.34+10.40
I need result as : 112.09
Your code works fine for me, after minimal corrections:
const price = [[30.56, 1.014], [50.44, 1.019], [10.35, 1.081], [10.34, 1.115], [10.40, 2.006]]
var first = 0; // <-- here
var second = 0;
price.forEach(obj => {
first += +obj[0]; // <-- here
second += +obj[1]; // <-- here
});
console.log(first); // --> 112.09
console.log(second); // --> 6.2349
You can get four digits after dot this way:
var a = 1.23456789;
var b = 1234.56789;
var c = 16643.59000000003
const dot1000 = x => Math.round(x*10000)/10000;
console.log(dot1000(a));
console.log(dot1000(b));
console.log(dot1000(c));
Another implementation (with zeros at the end)
var a = 1.23456789
var b = 1234.56789
var c = 16643.59000000003
const dot1000 = x => parseInt(x) + '.' + (x+.00001+'').split('.')[1].slice(0,4)
console.log(dot1000(a))
console.log(dot1000(b))
console.log(dot1000(c))
Update
Modern JavaScript (ES2017) can add zeros this way:
console.log('123'.padEnd(5,'0')); // 12300
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padEnd
numbersInArray = price.flat()
let sum = 0
numbersInArray.forEach( number => sum += number)
Using Array.prototype.reduce() method, this becomes very easy:
const result = arr.reduce((total, el)=> {
return total + el[0] + el[1] // el = [a, b]
}, 0)
console.log(result) /// 118.325
Let me know in the comments if this is what you want or you want any improvements
You are adding the array in which each number (both obj[0] and obj[1] values) is treated as String type. So that's why they are not added like numbers but concatenated. First convert the String Type into Number. Then your problem will be resolved.
As I don't know about the used API. So I could not give answer with API response included. But I am giving you code where I do some changes but just look at the praseFloat() method that I used.
const Api_Response_Array = [["30.56", "1.014"], ["50.44", "1.019"], ["10.35", "1.081"], ["10.34", "1.115"], ["10.40", "2.006"]];
var first= 0;
var second= 0;
Api_Response_Array.forEach(function(){
first+= parseFloat(Api_Response_Array[0][0]);
second+= parseFloat(Api_Response_Array[0][1]);
});
document.write(first + "<br>");
document.write(second);
Just use praseFloat method inside function used within forEach loop. It will convert the string into number.
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.
I have an array of arrays in JavaScript that I'm storing some values in, and I'm attempting to find a way to clear the value within that array when the user removes the specified control from the page, however I'm not finding a good way to do this and anything I try doesn't seem to be working.
What is the best method for clearing the value in the array? I'd prefer the value to be null so that it's skipped when I iterate over the array later on.
I've tried to do MyArray[id][subid] = '' but that still is technically a value. I've also tried to do MyArray[id][subid].length = 0 but that doesn't seem to do anything either. Trying to grab the index and splice it from the array returns a -1 and therefore doesn't work either.
var MyArray;
window.onload = function(){
MyArray = new Array();
}
function EditValuesAdd(){
var Input = document.getElementById('Values-Input').value;
var ID = document.getElementById('FID').value;
var ValueID = ControlID(); // generate GUID
if (!MyArray[ID]) MyArray[ID] = new Array();
MyArray[ID][ValueID] = Input;
document.getElementById('Values').innerHTML += '<a href="#" id="FV-' + ValueID + '" onclick="EditValuesRemove(this.id)"/><br id="V-' + ValueID + '"/>';
}
function EditValuesRemove(id)
{
var ID = document.getElementById('FID').value;
document.getElementById(id).remove();
document.getElementById(id.replace('FV-', 'V-')).remove();
MyArray[ID][id.replace('FV-', '')] = '';
}
I've also tried to do an index of and then splice it from the underlying array but the index always returns -1.
var Index = MyArray[ID].indexOf(id.replace('FV-', ''));
MyArray[ID].splice(Index, 1);
Setting the length to zero has no effect either.
MyArray[ID][id.replace('FV-', '')].length = 0;
I would expect that one of the methods above would clear out the value and make it null so that it is skipped later on but all of the methods I've found and tried so far leave some non-null value.
What you need is an object (a Map), not an array (a list).
Here's a basic idea of how to do it :
MyArray = {};
....
if (!MyArray[ID]) MyArray[ID] = {}
MyArray[ID][ValueID] = Input;
...
delete MyArray[ID][id.replace('FV-', '')];
Check here for more information : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object
In the end I used an array of objects MyArray = [] and then using splice/findindex to remove it from the array:
function RemoveItem(id)
{
var Index = MyArray.findIndex(a => a.ID == id.replace('FV-', ''));
MyArray.splice(Index, 1);
document.getElementById(id).remove();
document.getElementById('FVB-' + id.replace('FV-', '')).remove();
}
It doesn't solve the actual question asked but I don't know if there really is an answer since I was using arrays in the wrong manner. Hopefully this at least points someone else in the right direction when dealing with arrays and objects.
I've read some question but I still can't figure out how to do it
I have a url example.com/event/14aD9Uxp?p=10
Here I want to get the 14aD9Uxp and the value of p
I've tried using split('/'+'?p=') but it doesn't work
I want to use regex but I dont really understand how to use it
var URL='example.com/event/14aD9Uxp?p=10';
var arr=URL.split('/');//arr[0]='example.com'
//arr[1]='event'
//arr[2]='14aD9Uxp?p=10'
var parameter=arr[arr.length-1].split('?');//parameter[0]='14aD9Uxp'
//parameter[1]='p=10'
var p_value=parameter[1].split('=')[1];//p_value='10';
I've created a generalized function (restricted in some ways) that will return the GET value given the parameter. However this function will only work correctly provided that you do not Rewrite the URL or modify the URL GET SYNTAX.
//Suppose this is your URL "example.com/event/14aD9Uxp?p=10";
function GET(variable) {
var str = window.location.href;
str = str.split("/");
// str = [example.com, event, 14aD9Uxp?p=10]
//Get last item from array because this is usually where the GET parameter is located, then split with "?"
str = str[str.length - 1].split("?");
// str[str.length - 1] = "14aD9Uxp?p=10"
// str[str.length - 1].split("?") = [14aD9Uxp, p=10]
// If there is more than 1 GET parameter, they usually connected with Ampersand symbol (&). Assuming there is more, we need to split this into another array
str = str[1].split("&");
// Suppose this is your URL: example.com/event/14aD9Uxp?p=10&q=112&r=119
// str = [p=10, q=112, r=119]
// If there is only 1 GET parameter, this split() function will not "split" anything
//Remember, there might only be 1 GET Parameter, so lets check length of the array to be sure.
if (str.length > 1) {
// This is the case where there is more than 1 parameter, so we loop over the array and filter out the variable requested
for (var i = 0; i < str.length; i++) {
// For each "p=10" etc. split the equal sign
var param_full_str = str[i].split("=");
// param_full_str = [p, 10]
//Check if the first item in the array (your GET parameter) is equal to the parameter requested
if (param_full_str[0] == variable) {
// If it is equal, return the second item in the array, your GET parameter VALUE
return param_full_str[1];
}
}
} else {
// This is the case where there is ONLY 1 GET parameter. First convert it to a String Type because Javascript decided that str was no longer a String
// Now split it with the equal sign.
str = str.toString().split("=");
return str[1];
}
}
document.write(GET("p"));
function $_GET(param) {
var vars = {};
window.location.href.replace(
/[?&]+([^=&]+)=?([^&]*)?/gi, // regexp
function( m, key, value ) { // callback
vars[key] = value !== undefined ? value : '';
}
);
if ( param ) {
return vars[param] ? vars[param] : null;
}
return vars;
}
I have collected this from here:
http://www.creativejuiz.fr/blog/javascript/recuperer-parametres-get-url-javascript
It works great.
To use it just grab your parameter like:
var id = $_GET('id');
const url = new URL('http://example.com/event/14aD9Uxp?p=10');
const [,, eventId ] = url.pathname.split('/');
const p = url.searchParams.get('p');
Browser support:
https://caniuse.com/#feat=url
https://caniuse.com/#feat=urlsearchparams
Simple no-regex way
var s = "example.com/event/14aD9Uxp?p=10";
var splitByForwardSlash = s.split('/');
// To get 14aD9Uxp
splitByForwardSlash[splitByForwardSlash.length-1]
// To get p=10
splitByForwardSlash[splitByForwardSlash.length-1].split('?')[1]
I think you know how to go from here :-)
I'm trying to break up a string like this one:
fname=bill&mname=&lname=jones&addr1=This%20House&...
I want to end up with an array indexed like this
myarray[0][0] = fname
myarray[0][1] = bill
myarray[1][0] = mname
myarray[1][1] =
myarray[2][0] = lname
myarray[2][1] = jones
myarray[3][0] = addr
myarray[3][1] = This House
The url is quite a bit longer than the example. This is what I've tried:
var
fArray = [],
nv = [],
myarray = [];
fArray = fields.split('&');
// split it into fArray[i]['name']="value"
for (i=0; i < fArray.length; i++) {
nv = fArray[i].split('=');
myarray.push(nv[0],nv[1]);
nv.length = 0;
}
The final product is intended to be in 'myarray' and it is, except that I'm getting a one dimensional array instead of a 2 dimensional one.
The next process is intended to search for (for example) 'lname' and returning the index of it, so that if it returned '3' I can then access the actual last name with myarray[3][1].
Does this make sense or am I over complicating things?
Your line myarray.push(nv[0],nv[1]); pushes two elements to the array myarray, not a single cell with two elements as you expect (ref: array.push). What you want is myarray.push( [nv[0],nv[1]] ) (note the brackets), or myarray.push(nv.slice(0, 2)) (ref: array.slice).
To simplify your code, may I suggest using Array.map:
var q = "foo=bar&baz=quux&lorem=ipsum";
// PS. If you're parsing from a-tag nodes, they have a property
// node.search which contains the query string, but note that
// it has a leading ? so you want node.search.substr(1)
var vars = q.split("&").map(function (kv) {
return kv.split("=", 2);
});
For searching, I would suggest using array.filter:
var srchkey = "foo";
var matches = vars.filter(function (v) { return v[0] === srchkey; });
NB. array.filter will always return an array. If you always want just a single value, you could use array.some or a bespoke searching algorithm.
for (var i = 0; i < fArray.length; i++) {
nv = fArray[i].split('=');
myarray.push([nv[0],nv[1]]);
}
nv.length = 0; is not required, since you're setting nv in each iteration of the for loop.
Also, use var i in the for-loop, otherwise, you're using / assigning a global variable i, that's asking for interference.