Is there a function for retrieving last array's element value? - javascript

I have an array of inputs that accepts a range of 0 and 1. var array = [0,1,0,0,1];//that is not static
Is there a function for retrieving the last element of the array?
function myfn(){
var array = [1,0,0,0,1,0]; //that may change depending on the user inputs
var b= 0;
let l = array.length;
for(b=0; b<l; b++)
if(array [l-1]==0)
document.getElementById('print').textContent = 'Last element is 0';
}//end function
P.S: I am editing this old and bad question in order to get give the community time to re-evaluate it.

Please try this
function myfn(){
var array = [1,0,0,0,1,0]; //that may change depending on the user inputs
var b=0;
if(array[array.length-1] == 0)
document.getElementById('print').textContent = 'Last element is 0';
}

You could take the length of the array and reduce it by 1 and take the element at this position for checking. You need no loop for the access.
if (array[array.length - 1] === 0) {

Doesn't really need a function, you can even write it inline.
function last_element_is_0(arr){
return !arr[arr.length -1]
}
function myfn(){
var array = [1,0,0,0,1,0]; //that may change depending on the user input
if(last_element_is_0(array))
document.getElementById('print').textContent = 'Last element is 0';
}

Related

How to iterate through possible null values in javascript without errors

I have up to 100 inputs on my screen, each one has either a numerical value, or is null (as its not been loaded onto the screen yet), I want to be able to take the value's of each of these inputs, and add them together to get a final value.
I have attempted this with a for loop, iterating through them, but once it gets to the null value ones, it returns 'NaN' error.
The first input is called 'Input1', the second 'Input2' etc...
My code below:
var val = 0; //assigning the final value OUTSIDE the for loop to stop it assigning itself as 0 every loop
for (var calc = 0; calc < 100; calc++) //less than 100 as of 100 inputs
{
var inputVal = $('#Input'+calc).val(); //grabbing each input on screen
var floatVal = parseFloat(inputVal); // converting each value to float
var finalVal = finalValue + floatVal; //takes the val of 0, and adds each input value onto it per loop
}
alert(finalVal);
This always returns 'NaN'.
If I set the for loop to 'calc < 2' for example, and load 2 inputs on the screen, it will work, so I'm assuming its because the other values are null?
Thank you
You can use the Number.isNaN(value) function to skip to the next loop iteration if the value is NaN.
Noticed in your code you declare val but then never use it, instead you declare a new finalVal on every loop. You should declare finalVal before the loop and add to it on every iteration, as such:
var finalVal = 0;
for (var i = 0; i < 100; i++)
{
var inputVal = $('#Input'+i).val();
var floatVal = parseFloat(inputVal);
if (Number.isNaN(floatVal))
{
continue;
}
finalVal += floatVal;
}
alert(finalVal);

Give structure to 'random' function js?

I have an array and a function that picks randomly elements from this array and displays them in a div.
My array:
var testarray = [A, B, C, D, E, F];
Part of the js function:
var new_word = testarray[Math.floor((Math.random()*testarray.length)+1)];
$("#stimuli").text(new_word);
My question is, is there a way I can have them picked randomly in a certain ratio/order?
For example, that if I have my function executed 12 times, that each of the six letters is displayed exactly twice, and that there can never be the same letter displayed twice in a row?
You might want to try a quasi-random sequence. These sequences have the properties you're after. http://en.wikipedia.org/wiki/Low-discrepancy_sequence
Edit:
To your question in the comment: Of course there are hundreds ways to solve a problem. Think about using artificial intelligence, a mathematical algorithm or the answers given by others here. It depends on what you really want to achieve. I just gave a robust solution that is easy to understand and implement..
Here's another (different approach), same result but with the prevention that values displays twice in a row.
Jsfiddle: http://jsfiddle.net/kychan/jJE7F/
Code:
function StructuredRandom(arr, nDisplay)
{
// storage array.
this.mVar = [];
this.previous;
// add it in the storage.
for (var i in arr)
for (var j=0; j<nDisplay; j++)
this.mVar.push(arr[i]);
// shuffle it, making it 'random'.
for(var a, b, c = this.mVar.length; c; a = Math.floor(Math.random() * c), b = this.mVar[--c], this.mVar[c] = this.mVar[a], this.mVar[a] = b);
// call this when you want the next item.
this.next = function()
{
// default value if empty.
if (this.mVar.length==0) return 0;
// if this is the last element...
if (this.mVar.length==1)
{
// we must give it..
return this.mVar.pop();
// or give a default value,
// because we can't 'control' re-occuring values.
return -1;
}
// fetch next element.
var element = this.mVar.pop();
// check if this was already given before.
if (element==this.previous)
{
// put it on top if so.
this.mVar.unshift(element);
// call the function again for next number.
return this.next();
}
// set 'previous' for next call.
this.previous = element;
// give an element if not.
return element;
};
}
NOTE: In this example we can't fully control that the same values are displayed twice.. This is because we can control the first numbers, but when there is only one number left to display, we must either give it or display a default value for it, thus there is a chance that the same value is shown.
Good luck!
Like this?
var arr = [1,2,3,4,5,6,7], // array with random values.
maxDispl = 2, // max display.
arr2 = init(arr) // storage.
;
// create object of given array.
function init(arr)
{
var pop = [];
for (var i in arr)
{
pop.push({value:arr[i], displayed:0});
}
return pop;
}
// show random number using global var arr2.
function showRandom()
{
// return if all numbers has been given.
if (arr2.length<1) return;
var randIndex= Math.floor(Math.random()*arr2.length);
if (arr2[randIndex].displayed<maxDispl)
{
document.getElementById('show').innerHTML+=arr2[randIndex].value + ', ';
arr2[randIndex].displayed++;
}
else
{
// remove from temp array.
arr2.splice(randIndex, 1);
// search for a new random.
showRandom();
}
}
// iterate the function *maxDispl plus random.
var length = (arr.length*maxDispl) + 2;
for (var i=0; i<length; i++)
{
showRandom();
}
jsfiddle: http://jsfiddle.net/kychan/JfV77/3/

Taking values from one array and to obtain a different value from a separate array. JavaScript

I'm not entirely sure how to word what I am asking here but I have an assignment where two arrays are present. One array contains strings which are the makes of cars. The second array contains the price of that car. The program is to run a for loop through the first array, identify the values that contain that specific make, and then add the prices up in the second array.
This is what I have:
<html>
<script>
make = new Array();
make[0]='honda';
make[1]='toyota';
make[2]='pontiac';
make[3]='honda';
price = new Array();
price[0]=35000;
price[1]=35000;
price[2]=40000;
price[3]=45000;
function totalByColor(parameter1){
total=0;
for(i=0;i<make.length;i++){
if(make[i]=='honda'){
for(b=0;b<price.length;b++){
make[i]=price[b]; //This is where I need help!
total = total + price[b];
};
} else {
};
return total;
};
return total;
};
</script>
<input type='button' value='test' onclick="alert('Return = '+totalByColor('honda'))">
</html>
So I need to set the program up to identify the value in make[0] is relevant to price[0] and make[3] is relevant to price[3], so price[0] and price[3] can be added together in the second for loop, any one have any idea? Thanks in advance for any help or guidance on this issue
If the indices are the same, you don't need another for loop; just use your var i:
var total = 0;
for (var i = 0, len = make.length; i < len; i++) {
if (make[i] === 'honda') {
total += price[i];
}
}
return total;
total should be a local variable, and is defined as 0 first, then you can use += to redefine total as total + price[i]. It's shorthand for total = total + price[i]. I also included var before the i in the for loop, because it should be local, and not global; and, you don't need so many semi-colons: after brackets for example } (so long as it's not an object you are defining). One more thing is that you have a return statement in your for loop, which means it will only loop over one value before ending the function. The return statement should be after the for loop.

Can I select 2nd element of a 2 dimensional array by value of the first element in Javascript?

I have a JSON response like this:
var errorLog = "[[\"comp\",\"Please add company name!\"],
[\"zip\",\"Please add zip code!\"],
...
Which I'm deserializing like this:
var log = jQuery.parseJSON(errorLog);
Now I can access elements like this:
log[1][1] > "Please add company name"
Question:
If I have the first value comp, is there a way to directly get the 2nd value by doing:
log[comp][1]
without looping through the whole array.
Thanks for help!
No. Unless the 'value' of the first array (maybe I should say, the first dimension, or the first row), is also it's key. That is, unless it is something like this:
log = {
'comp': 'Please add a company name'
.
.
.
}
Now, log['comp'] or log.comp is legal.
There are two was to do this, but neither avoids a loop. The first is to loop through the array each time you access the items:
var val = '';
for (var i = 0; i < errorLog.length; i++) {
if (errorLog[i][0] === "comp") {
val = errorLog[i][1];
break;
}
}
The other would be to work your array into an object and access it with object notation.
var errors = {};
for (var i = 0; i < errorLog.length; i++) {
errors[errorLog[i][0]] = errorLog[i][1];
}
You could then access the relevant value with errors.comp.
If you're only looking once, the first option is probably better. If you may look more than once, it's probably best to use the second system since (a) you only need to do the loop once, which is more efficient, (b) you don't repeat yourself with the looping code, (c) it's immediately obvious what you're trying to do.
No matter what you are going to loop through the array somehow even it is obscured for you a bit by tools like jQuery.
You could create an object from the array as has been suggested like this:
var objLookup = function(arr, search) {
var o = {}, i, l, first, second;
for (i=0, l=arr.length; i<l; i++) {
first = arr[i][0]; // These variables are for convenience and readability.
second = arr[i][1]; // The function could be rewritten without them.
o[first] = second;
}
return o[search];
}
But the faster solution would be to just loop through the array and return the value as soon as it is found:
var indexLookup = function(arr, search){
var index = -1, i, l;
for (i = 0, l = arr.length; i<l; i++) {
if (arr[i][0] === search) return arr[i][1];
}
return undefined;
}
You could then just use these functions like this in your code so that you don't have to have the looping in the middle of all your code:
var log = [
["comp","Please add company name!"],
["zip","Please add zip code!"]
];
objLookup(log, "zip"); // Please add zip code!
indexLookup(log, "comp"); // Please add company name!
Here is a jsfiddle that shows these in use.
Have you looked at jQuery's grep or inArray method?
See this discussion
Are there any jquery features to query multi-dimensional arrays in a similar fashion to the DOM?

Get a limit on arrays (Javascript)

I've a problem with set a limit into my own lightbox for a gallery
<script>
var imagenumber = 0;
function btnleft(){
load = imagenumber-=1;
document.getElementById('lightboxcontent').innerHTML=imagelist[load];
}
function btnright(){
load = imagenumber+=1;
if (load==undefined){load=imagenumber-=1}
document.getElementById('lightboxcontent').innerHTML=imagelist[load];
}
</script>
Then the array
var imagelist=new Array(); // regular array (add an optional integer
imagelist[0]="image1.jpg"; // argument to control array's size)
imagelist[1]="image2.jpg";
imagelist[2]="image3.jpg";
When I click more then 3 times on the next button I got the error-message "undefined".
How should I do to get a limit on my arrays?
Try it with
function btnleft(){
var load = imagelist[imagenumber-=1];
if (load) // imagenumber in array boundaries
document.getElementById('lightboxcontent').innerHTML = load;
else
imagenumber = 0;
}
function btnright(){
var load = imagelist[imagenumber+=1];
if (load) // imagenumber in array boundaries
document.getElementById('lightboxcontent').innerHTML = load;
else
imagenumber = imagelist.length-1;
}
Yet, Arrays in Javascript have no limited size, they are more like (infinite) lists. You can hardly set a limit on their length - espcially not with the constructor, whose number argument is just for initialisation purposes.
You can use the length property of an array to check whether your index is in the array boundaries: i >= 0 && i < arr.length. My code just checks whether there is an item at that index (as your second function seems to intend, too) and resets the index otherwise.
I assume that clicking on the "next button" calls the btnright() function.
If that is the case then you are testing the wrong value for undefined. You could rewrite your function as:
function btnright(){
load = imagenumber += 1;
// Test the value at the index of the array, not your index variable.
if (imagelist[load] === undefined) {
load = imagenumber-= 1;
}
document.getElementById('lightboxcontent').innerHTML = imagelist[load];
}
Stylistically this is still no the best. Your load variable is not required since its value always duplicates imagenumber. You could refactor the function such:
function btnright() {
// If we have a new array value do something.
if (imagelist[imagenumber + 1] !== undefined) {
// Increment the index and load the new image.
document.getElementById('lightboxcontent').innerHTML = imagelist[++imagenumber];
}
}
function btnleft() {
// If we're not on the first image do something.
if (imagenumber !== 0) {
// Decrement the index and load the new image.
document.getElementById('lightboxcontent').innerHTML = imagelist[--imagenumber];
}
}

Categories