Create new objects inside of a function with JavaScript? - javascript

So I want to create a function that if, if a question is answered wrong, it stores the wrong answer into a new object? So that I can list all of the wrong answers at the end?
var answerList = [{question:1, answer:1},{question:2, answer:2},]
var listofWrongAnswers = [];
if (answerSelected != answerlist[1].answer) {
/* create a new object
put answerlist[1].question and answerlist[i].answer in new object and push to
array ListofWrongAnswers */
}
I dont get how you can randomly name variables? if that's even possible.

Couldn't you simply create a new object based on the current question?
Something like this should work:
if (answerSelected != answerlist[1].answer) {
listofWrongAnswers.push({question: answerlist[1].question, answer: answerlist[1].answer});
}
However, you should look to make that index a parameter:
function addToWrongAnswers(answerSelected, idx) {
if (answerSelected != answerlist[idx].answer) {
listofWrongAnswers.push({question: answerlist[idx].question, answer: answerlist[idx].answer});
}
}

I assume you want something like this:
function getQuestion(number){
for(var i = 0; i < answerList.length; i++){
if(answerList[i].question === number){
return answerList[i];
}
}
}
function checkAnswer(questionNumber, answer){
var question = getQuestion(questionNumber);
if(answer !== question.answer){
listofWrongAnswers[question];
}
}
However, I'm also assuming you'll start with Question 1 and increment the number, so it would be even simpler if you just selected the question using an array index, rather than iterating through it. So this might be better:
var answerList = [{question:1, answer:1}, {question:2, answer:2}];
var listofWrongAnswers = [];
function checkAnswer(questionNumber, answer){
var question = answerList[questionNumber - 1];
if(answer !== question.answer){
listofWrongAnswers[question];
}
}

If you want to clone that question object and push it into that array, you can use
listofWrongAnswer.push({question: answerlist[1].question, answer: answerlist[1].answer});
But with this code you won't can use == operator to compare question objects existing at those arrays
listofWrongAnswer[1] == answerlist[1] // It's false
But if you don't want such a behavior you can store only references to question objects in the wrong answer list:
listofWrongAnswer.push(answerlist[1]);
With this code you can compare question objects with == operator
listofWrongAnswer[1] == answerlist[1] // It's true

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 ) ".

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.

How to compare the values of a particular key from both arrays using inArray in jQuery

I have two array with objects inside in it. I want to compare the values of a particular key from both arrays and do something with that. I have tried using inArray but couldn't succeed. Below is my code.
function initialize() {
geometry = 'http://yyyy.cartodb.com/api/v2/sql?q=SELECT name,ST_AsGeojson(the_geom) from msa_usa';
$.getJSON(geometry,
function(data) {
var place_names = [];
place_names.push({
name: "Abilene",
average: 8.65
});
for (i = 0; i < place_names.length; i++) {
if ($.inArray(data.rows[i].name, place_names[i].name) > -1) {
geom.push((data.rows[i].st_asgeojson));
average_value.push(place_names[i].average);
} else
(console.log("else"));
//console.log(place_names[i].name);
}
})
}
console.log(average_value.length);
console.log(geom.length);
I'm not sure why you're trying to use $.inArray() at all. It appears you're just trying to compare two properties on two objects (which happen to be in arrays, but you're already indexing to a particular object). If that's the case, then you can just directly compare the two properties:
if (data.rows[i].name === place_names[i].name)
But, in your code, you appear to have just created place_names so it will only have one value in it, not a whole bunch of values in it. So, now that confuses me as to what you're really trying to do here.
For more help, please describe in words what you're really trying to accomplish. Are you just trying to see if one particular .name property is in the data.rows array of objects?
If so, that would be a different piece of code like this:
function findPropInArray(array, propName, value) {
for (var i = 0; i < array.length; i++) {
if (array[i][propName] === value) {
return i;
}
}
return -1;
}
Then, in your code you could use something like this:
if (findPropInArray(data.rows, "name", "Abilene") !== -1) {
// "Abilene" was as a name property in data.rows
}

How can I pick data out of an array in a object and insert it into another array in an object in Javascript?

I have variable qstore that's has an ans array containing a list of responses. The field named r is used to hold the response data (true or false) and is stored in an array called ans
qstore: {"id":2,
"qId":2,
"ans":[{"r":true},
{"r":true},
{"r":false},
{"r":false},
{"r":false}]}
Another variable qview:
qview: {"problemId":2,
"questionId":1,
"answer":null,
"text":"xx",
"answers":[{"answerId":1,
"response":false},
{"answerId":2,
"response":false},
{"answerId":3,
"response":false},
{"answerId":4,
"response":false},
{"answerId":5,
"response":false}]}
What I need to do is IF there is an array called ans in qstore (there may not be one) then I need to take the answer responses field r and use that to update the answers response field in the qview object. Note that the qview and qstore if they do have answers will always have the same number of answers.
Can anyone tell me a simple way that I can do this?
What I need to do is IF there is an array called ans in qstore (there may not be one) then I need to take the answer responses field r and use that to update the answers response field in the qview object. Note that the qview and qstore if they do have answers will always have the same number of answers.
// assuming `qstore`, `qview`
var i, j, ans = qstore.ans;
if (ans) { // if qstore has non-falsy ans
qstore: for (i = 0, j = 0; i < ans.length; ++i) { // loop over ans
for (; j < qview.answers.length; ++j) { // look in qview
if (qview.answers[j].answerId === i + 1) { // qview has already
qview.answers[j].response = ans[i].r;
continue qstore; // go back to looping ans
} else if (qview.answers[j].answerId <= i) { // qview needs new
break; // get out of qview loop
}
} // if we reach here then qview didn't have an entry for this item
qview.answers.splice(j, 0, { // insert new entry
'answerId': i + 1,
'response': ans[i].r
});
}
}
Just simply loop over the qstore.ans array (if it exists) and set the respective value in qview.
if(qstore.hasOwnProperty('ans')){
for(var i = 0, len = qstore.ans.length; i < len; i++){
qview.answers[i].response = qstore.ans[i].r;
}
}
JavaScript has an multiple ways to check if a key exists in an object: in and Object.hasOwnProperty. The difference between the two is that in also returns true if the key is found in the prototype chain of your object.
Now it appears the id's of your response are 1-indexed, but that doesn't matter if we iterate over the index of its position in the array itself:
if ('ans' in qstore) {
for (var i = 0; i <= qstore.ans.length; i++) {
qview.answers[[i].response = qstore.ans[i].r
}
}
There's also a nicer forEach available, if you're not expecting to support IE8 and earlier, or are prepared to insert a "shim":
if ('ans' in qstore) {
qstore.ans.forEach(function(element, index) {
element.response = qstore.ans[index].r
})
}
The most simple solution.
This way it will execute only if you have at less, 1 register on ans array, i see that the solutions above do not verify if the ans array have registers, so i think it is the right one for your case.
Here is the code:
if (qstore.ans != null){
if (qstore.ans.length > 0){
for (i=0;i<qstore.ans.length);i++){
qview.answers[i].response = qstore.ans[i].r;
}
}
}

How to find if a value matches one of the values from an array in Javascript [duplicate]

This question already has answers here:
How do I check if an array includes a value in JavaScript?
(60 answers)
Closed 6 years ago.
FYI: this is for a simple quiz with just a single input field for each answer.
I have the following Javascript if statement to check if the value entered into an input field is correct (in this case, if the value entered is 'england').
$('input').keyup(function () {
if ($(this).val().toLowerCase() == 'england') {
//Stuff
} else {
//Other Stuff
};
});
However, I want to allow for alternative spellings, so I need a few possible answers for each question - it seems sensible to use an array for this as so...
var ans1 = new Array();
ans1[0] = "England";
ans1[1] = "Englund";
ans1[2] = "Ingland";
How can I change my if statement to say 'if the input field value equals any of those values from the array, then do the following'?
Any help would be greatly appreciated! Thank you.
You can do this using .inArray():
if ($.inArray($(this).val(), ans1) > -1) {
//Stuff
}
Here, the code $.inArray($(this).val(), ans1) will search for a specified value for example England within an array ans1 and return its index (or -1 if not found).
UPDATE
For case-sensitive search:
First enter all the values in the array in Lower Case
Next use the code below:-
JS:
if ($.inArray($(this).val().toLowerCase(), ans1) > -1) {
//Stuff
}
You can use the 'indexOf' method of the array, this will return -1 if the value doesn't exist in the array:
//if answer is in array
if(array.indexOf(answer) != -1){
//do stuff
}else{
//do stuff
}
Try this
if(this.value.match(/^(England|Englund|Ingland)$/i))
using regex and gi modifier for case insensitive
Do like this
$('input').keyup(function () {
var ans1 = new Array();
ans1[0] = "England";
ans1[1] = "Englund";
ans1[2] = "Ingland";
for(int i=0;i<ans1.length;i++)
{
if ($(this).val().toLowerCase() ==ans1[i]) {
//Stuff
} else {
//Other Stuff
};
}
});
Perhaps you may consider checking each element of the array like that:
var ans1 = new Array();
ans1[0] = "England";
ans1[1] = "Englund";
ans1[2] = "Ingland";
$('input').keyup(function () {
for (var i = 0; i < ans1.length; i++) {
if ($(this).val().toLowerCase() == ans1[i]) {
//Stuff
} else {
//Other Stuff
};
}
});
Not the most beautiful solution, but it should work.
jQuery offers $.inArray:
var found = $.inArray('specialword', words) > -1;
Note that inArray returns the index of the element found, so 0 indicates the element is the first in the array. -1 indicates the element was not found.
put your spellings in an array like this:
words: [
"England"
"Inglund"
"Ingland"
]
Found will be true if the word was found.
If you want the index of the matched word delete > -1 from the line.
Your code would be like this:
$('input').keyup(function () {
var found = $.inArray($(this).val(), words);
found > -1 ? //Stuff : //otherStuff;
});

Categories

Resources