Javascript - Selecting an element in a list - javascript

How do I select an element from a list using Javascript. Here is some of my code:
var score = 0;
var bin = 0;
var question = -1;
var answers = ['higher', 'lower', 'higher', 'lower', 'higher'];
function answer_question(response) {
if (response == 1) {
if (answer[question] == "higher"){
score ++;
console.log(score);
} else {
bin ++;
console.log("Bin: ");
console.log(bin);
}
}
else if (response == 0) {
if (answer[question] == "lower") {
score ++;
console.log(score);
} else {
bin ++;
console.log("Bin: ");
console.log(bin);
}
}
}
However it doesn't work, I think this is due to the
answer[question] == "higher"
Thanks for your help!

This is because of three things:
answer is not defined. I suspect you meant answers. This could be just a typo.
Even if you did answers[question], well, question = -1, and answers[-1] returns undefined in Javascript. JS does not have the concept of negative indexing, so you can't use negative numbers as index subscripts. Use any number between 0 and answers.length - 1 instead, like so:
answers[0] // returns 0th (first) element of answers array
You never increment or change question. Every time you run this code, answers[question] always returns the same thing. In that case, why do you even have that line?
To answer your question as stated, however, array elements can be accessed by index like so: array[index]. index can be any integer between 0 and one less than the length of the array.

Related

Using Javascript Array Filter method to apply logic [duplicate]

I have search through quite a lot of questions here, but havent found one that i think fits my bill, so if you know of one please link to it.
I have an array that i want to search through for a specific number and if that number is in the array, i then want to take an action and if not then another action.
I have something like this
var Array = ["1","8","17","14","11","20","2","6"];
for(x=0;x<=Array.length;x++)
{
if(Array[x]==8)
then change picture.src to srcpicture1
else
then change picture.src to srcpicture2
}
but this will run the lenght of the array and end up checking the last element of the array and since the last element is not 8 then it will change the picture to picture2.
Now i can see why this happens, i just dont have any ideas as to how to go about checking if an array contains a specific number.
Thanks in advance.
What you can do is write yourself a function to check if an element belongs to an array:
function inArray(array, value) {
for (var i = 0; i < array.length; i++) {
if (array[i] == value) return true;
}
return false;
}
And the just do:
var arr = ["1","8","17","14","11","20","2","6"];
if (inArray(arr, 8)) {
// change picture.src to srcpicture1
} else {
// change picture.src to srcpicture2
}
It's a lot more readable to me.
For extra points you can add the function to the array prototype like so:
Array.prototype.has = function (value) {
for (var i = 0; i < this.length; i++) {
if (this[i] === value) return true;
}
return false;
};
And then the call would be
if (arr.has(8)) // ...
Pushing this even further, you can check for indexOf() method on array and use it - if not - replace it with the code above.
P.S. Try not to use Array for a variable name, since it's reserved for the actual array type.
use this
http://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Objects/Array/IndexOf
ie version
https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Objects/Array/IndexOf#Compatibility
Why don't just you abort the loop when you find the right number :
for(x=0;x<=Array.length;x++)
{
if(Array[x]==8) {
//change picture.src to srcpicture1
break;
}
}
You could sort the array first then check the array only up to the point at which a number would be in the array, were it to exist.
If you have unique keys and a faster retrieval is what you care about a lot, you can consider using a map instead of an array (if there's a hard-bound case of using an array, then it won't work of course). If using a map, you just check "if( num in arr ) ".

How to find the missing next character in the array?

I have an array of characters like this:
['a','b','c','d','f']
['O','Q','R','S']
If we see that, there is one letter is missing from each of the arrays. First one has e missing and the second one has P missing. Care to be taken for the case of the character as well. So, if I have a huge Object which has all the letters in order, and check them for the next ones, and compare?
I am totally confused on what approach to follow! This is what I have got till now:
var chars = ("abcdefghijklmnopqrstuvwxyz"+"abcdefghijklmnopqrstuvwxyz".toUpperCase()).split("");
So this gives me with:
["a","b","c","d","e","f","g","h","i","j","k","l","m",
"n","o","p","q","r","s","t","u","v","w","x","y","z",
"A","B","C","D","E","F","G","H","I","J","K","L","M",
"N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
Which is awesome. Now my question is, how do I like check for the missing character in the range? Some kind of forward lookup?
I tried something like this:
Find the indexOf starting value in the source array.
Compare it with each of them.
If the comparison failed, return the one from the original array?
I think that a much better way is to check for each element in your array if the next element is the next char:
function checkMissingChar(ar) {
for (var i = 1; i < ar.length; i++) {
if (ar[i].charCodeAt(0) == ar[i-1].charCodeAt(0)+1) {
// console.log('all good');
} else {
return String.fromCharCode(ar[i-1].charCodeAt(0)+1);
}
}
return true;
}
var a = ['a','b','c','d','f']
var b = ['O','Q','R','S']
console.log(checkMissingChar(a));
console.log(checkMissingChar(b));
Not that I start to check the array with the second item because I compare it to the item before (the first in the Array).
Forward Look-Ahead or Negative Look-Ahead: Well, my solution would be some kind of that. So, if you see this, what I would do is, I'll keep track of them using the Character's Code using charCodeAt, instead of the array.
function findMissingLetter(array) {
var ords = array.map(function (v) {
return v.charCodeAt(0);
});
var prevOrd = "p";
for (var i = 0; i < ords.length; i++) {
if (prevOrd == "p") {
prevOrd = ords[i];
continue;
}
if (prevOrd + 1 != ords[i]) {
return String.fromCharCode(ords[i] - 1);
}
prevOrd = ords[i];
}
}
console.log(findMissingLetter(['a','b','c','d','f']));
console.log(findMissingLetter(['O','Q','R','S']));
Since I come from a PHP background, I use some PHP related terms like ordinal, etc. In PHP, you can get the charCode using the ord().
As Dekel's answer is better than mine, I'll try to propose somewhat more better answer:
function findMissingLetter (ar) {
for (var i = 1; i < ar.length; i++) {
if (ar[i].charCodeAt(0) != ar[i-1].charCodeAt(0)+1) {
return String.fromCharCode(ar[i-1].charCodeAt(0)+1);
}
}
return true;
}
var a = ['a','b','c','d','f']
var b = ['O','Q','R','S']
console.log(findMissingLetter(a));
console.log(findMissingLetter(b));
Shorter and Sweet.

indexOf ignores second character in array

I'm just studying JS and I need to write a program that checkes if the string in the first element of the array contains all of the letters of the string in the second element of the array.
I've made a code like this:
function mutation(arr) {mutation: {
var lowerCaseStringOne = arr[0].toLowerCase();
var lowerCaseStringTwo = arr[1].toLowerCase();
if (lowerCaseStringOne === lowerCaseStringTwo) {
console.log(true);
break mutation;
}
var newArray = [];
for (var i = 0; i < lowerCaseStringTwo.length; i++){
console.log(lowerCaseStringTwo[i]);
if (lowerCaseStringTwo.indexOf(lowerCaseStringOne[i]) > 0) {
newArray.push(lowerCaseStringTwo[i]);
console.log('---');
}
}
var result = newArray.join("");
if (result === lowerCaseStringTwo) {
console.log(true);
} else {
console.log(false);
}
}
}
mutation(["Mary", "Aarmy"]);
I think it's very complicated, but I can't solve the problem - the "indexOf" function seems to ignore a second character in my loop - loggs it in the console but doesn't pushes into an array. I thought it could happen because first and second letters are similar, but it's not. No matter what letter, it just ignores it.
indexOf() will return 0 for the letter "a" in your example as the first instance is at position 0 in the array.
You should be using ">= 0"

json array check if there does not need to insert in localstorage?

I need to check a JavaScript array to see if there are duplicate values ​​. What is the easiest way to do this ? I just need to check whether the values ​​already exist if there is not need to go into json array.
function cek() {
resi_or_code = document.getElementById('code_or_resi').value;
resi = resi_or_code.split(',');
if($.trim(resi_or_code) != ''){
location.href = base_url + 'resi/' + encodeURIComponent(resi_or_code);
}
if (localStorage.daftar_data){
daftar_data = JSON.parse(localStorage.getItem('daftar_data'));
$("#riwayat").toggle();
}
else {
daftar_data = [];
}
for (y in daftar_data){
var q = daftar_data[y].resis;
for (x in resi){
console.log(q);
if (q === resi[x])
{
console.log('Value exist');
}else{
console.log('Value does not exist');
daftar_data.push({'resis':resi[x]});
localStorage.setItem('daftar_data', JSON.stringify(daftar_data));
}
}
}
}
If i understand your question and code right, you basically have an array of objects where each object has key resis
If that is the case, below code might help
var valueArray = ar.map(function(item) {
return item.resis;
})
// To check for duplicate
if(valueArray.indexOf(value) !== -1) {
// Duplicates
} else {
// No duplicate
}
In your case,
ar would be daftar_data.
I am really not sure what your value is. is it resi?
Basically, you should try replacing your for loop with the above code.
By far the simplest way is to simply sort your array using Array.sort(). This will perform well and reduces you duplicate check to a simple for-loop that compares each value with its neighbor.
Solutions that attempt to avoid sorting will almost certainly scale very badly.
So to recap and show some code:
daftar_data.sort();
for (var index = 0; index < daftar_data.length - 1; index++)
{
if (daftar_data[index] === daftar_data[index+1]) {
// Found a duplicate
}
}
If the natural sort order of the objects don't work for you, supply a function to the sort function, like so:
daftar_data.sort(function(a, b) {
// return any value > 0 if a is greater, < 0 if b is greater
// and 0 if they are equal.
});
Note that in this form, you can actually check for the duplicate in your compare function.

JS: Using Length Property to Write If Statement

I'm very new to JS so go easy on me. I've got this array inside a variable, and am trying to find a better way to write that if statement. So if the names inside that variable grow, I won't need to change the if statement as it won't be hardcoded.
var names = ["beth", "barry", "debbie", "peter"]
if (names[0] && names [1] && names [2] && names [3] {
Do something...
}
Something tells me I need to be using the .length property but I can't work out how to properly use it within that statement. Something along the lines of:
if (names[i] * names.length) {
Do something...
}
I know that's wrong. I think need to be finding the index of each and looping through it makign sure it the loop doesn't exceed the amount of values in the array.
Any help is appreciated. Thanks in advance!
Update: Some users have alerted me that my question might not be as clear. I've setup a CodePen here (http://codepen.io/realph/pen/KjCLd?editors=101) that might explain what I'm trying to achieve.
P.S. How do I stop my from repeating 3 times?
You can use every to test whether every element satisfies some condition:
if (names.every(function (name) { return name })) {
// Do Something
}
every will automatically stop testing when the first non-true element is found, which is potentially a large optimization depending on the size of your array.
Traditionally, you would simply iterate over the array and test each element. You can do so with forEach or a simple for loop. You can perform the same early-termination when you find a non-true element by returning false from the forEach callback.
var allTrue = true;
names.forEach(function (name) {
return allTrue = allTrue && name;
});
if (allTrue) {
// Do something...
}
Please give a english description of what you are trying to accomplish. The below answer assumes you simply want to iterate a list of names and do some processing with each.
You want to use a for loop.
var names = ["beth", "barry", "debbie", "peter"]
for (var i=0; i<names.length; i++) {
// access names[i]
}
The best cross-browser solution is to use a traditional for loop.
var names = ["beth", "barry", "debbie", "peter"],
isValid = true,
i;
for (i = 0; i < names.length; i++) {
isValid = isValid && names[i];
}
if (isValid) {
// do something
}
You can try this;
var checkCondition = true;
for(var i = 0; i<names.length; i++){
if(names[i] !== something) {
checkCondition = false;
break;
}
}
if(checkCondition){
//Do what ever you like if the condition holds
}else{
// Do whatever you like if the condition does NOT holds
}
If i understand right you need something like this
var names = ["beth", "barry", "debbie", "peter"];
var notUndefinedNames = names.filter(function(el){return el !== undefined;});
// if all
if (names.length === notUndefinedNames.length) console.log("You're all here. Great! Sit down and let's begin the class.");
// if one or less
else if (notUndefinedNames.length <= 1) console.log("I can't teach just one person. Class is cancelled.");
else console.log("Welcome " + notUndefinedNames.join(', '));

Categories

Resources