creating a multiple choice quiz with array - javascript

I am a complete beginner and I am working on creating a multiple choice quiz using array. The questions have the same format " Which word in the following has a similar meaning to '_________' ". So I create an array(?) that store all the words I want to put in '________' and another array that contain answers correspond to it.
var ques=['apple', 'pencil' ,'juice'];
var ans= ['orange', 'pen','water'];
However, as I want to create a few hundreds of questions, I think it is quite troublesome to do it in the following way.
var querep=[ ['apple','orange'], ['pencil','pen'],['juice','water'] ];
so i try doing this instead:
var querep=[ [ques, ans] ];
and yes, i know it makes no sense to u all, but i just want to merge the two array lists and allow it to do the same function as
var querep
example questions:
which word in the following has similar meaning to apple?
A.pen
B.writer
C.orange
D.vegetable

This answer may not be fulfilled with your approach. But you can have it as reference for data structure design. Since years ago I did something similar to this and finally found myself immerse in refactor phase and re-do a lot of parts.
I can tell you may have a big list of question survey, when it comes to long list. You should think of it as a big object. Not a usual Array like the approach you're implementing, because it's faster for any things related to find/ traverse purpose.
So, basically the data might look like this:
const questions = {
"apple": "orange",
"water": "juice",
"chicken": "duck",
...
}
You still can iterate through an object with {key,value} pair and your problem is solved.
In real scenario, I think the data structure might be a more complicated, usually each will have its own _id, so the object might look like this, but the approach of iterating doesn't change.
const questions = {
"12312311414": {
id: "12312311414",
quesion: "apple",
accept: "orange",
},
"12312311415": {
id: "12312311415",
quesion: "water",
accept: "juice",
},
...
}
So, before deciding merging two arrays, I hope you can change your mind.

If you want to use a merged array as mentioned in question, you could use map function on array to create a new array. Here new querep array should be in the format as you want:
var ques=['apple', 'pencil' ,'juice'];
var ans= ['orange', 'pen','water'];
var querep = ques.map(function(val, index){
return [val, ans[index]]
});

plan like this.
// At first write all your questions , options and answers here.
var questions = [
{"question" : "what is the capital of india?" , "options" : ["hyderabad","delhi","chennai","bengalore"], "answer" : "hyderabad"},
{"question" : "what is even number?" , "options" : [1,3,5,8], "answer" :8}
];
// you will get question along with question number here
var questions_list = {}; var i = 1;
$.each(questions ,function(k,v){
questions_list[i] = v;
i++;
});
console.log(questions_list);

Related

How does manipulating multiple checkbox selection code work?

I am following ag-grid's official tutorial:
https://www.ag-grid.com/angular-getting-started/?utm_source=ag-grid-readme&utm_medium=repository&utm_campaign=github
I reached the part where I have to manipulate the information regarding the selected checkboxes. However, the documentation is not detailed; It does not explain how the code actually works. Perhaps, this makes sense since it is not their job to explain in detail. However, for someone like me who doesn't have solid experience with working with angular technology and who wants to truly understand how things work, this is troublesome!
In the html file, I have been asked to add this:
<button (click)="getSelectedRows()">Get Selected Rows</button>
And in app.component.ts, I have been asked to add this:
getSelectedRows() {
const selectedNodes = this.agGrid.api.getSelectedNodes();
const selectedData = selectedNodes.map(node => node.data);
const selectedDataStringPresentation = selectedData.map( node => node.make + ' ' + node.model).join(', ');
alert('Selected nodes: ${selectedDataStringPresentation}');
}
If someone could explain what the typescript code is doing exactly, that would be very generous.
Thank you!
I guess agGrid is the service storing your mock values, this simply gets an array of data from somwhere.
selectedData is another array that is created by transforming (transforms the array while providing a new reference, thus not modifying the original array) the selectedNodes array and only selecting the data property of each node.
selectedDataStringPresentation is the same, but this time it provides an array of formatted strings by merging the properties make and model of each object from selectedData.
What you probably fail to grasp is the usage of the ES6 (JavaScript standard) functions that are used here, and especially the map() function.
Here is the official documentation of the map() function for arrays : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map
Simply explained, it is a function that iterates over an array, and transforming each object by applying the function declared in the map, returning the results in a new array.
If you take the example of selectedData, you can translate the operation into this :
Loop over each object of selectedNodes, and return only the property data of the current object. Push the results in a new array.
This is especially useful when you want to work on different arrays that serve different purposes. For example, imagine you have a service that contains a list of objects. A backend service will provide you an array of numbers representing the IDs of the objects you have in your service.
You can then use the map() function to transform the array of IDs into an array of your Objects stored in your service easily.
Darn #Alex Beugnet(upvote) beat me to the punch! I'm going to post anyway as I was in the middle of writing it all.
Firstly I'm not sure how much of TypeScript you already know, I apologize if much of these becomes trivial, the purpose is only to ensure maximum clarification to the question in understanding the logic.
In the Enable Selection portion of the guide, you are essentially enabling multiple row selection in the grid and having the button return the data from those selected rows.
In order to see what's happening with the getMultipleRows() function, it would be best to visualize it via the Debugger provided in browsers, I'm using Chrome Developer Tools (hit F12), I would highly recommend it for understanding what is happening in the logic.
const selectedNodes
Let's start by selecting say 2 rows, I have selected the Porsche Boxster 72000 and Ford Mondeo 32000. After selecting them I click on the 'Get Selected Rows' button which triggers the getSelectedRows() function:
const selectedNodes = this.agGrid.api.getSelectedNodes();
The above line is assigning the constant variable 'selectedNodes' the RowNodes from AgGrid. Here you are using the AgGridNg2 method getSelectedNodes() to return the selected node data, which you would be returned an array in the form of:
[RowNode, RowNode] //(each for the row we have selected)
Looking into a RowNode we get:
These are all the RowNode properties provided by the AgGrid framework, you can ignore all of these object properties as you are only concerned with the 'data' property as you'll see in the next line of code!
const SelectedData
const selectedData = selectedNodes.map(node => node.data);
Here we are setting 'selectedData' as an array of RowNode.data, basically trying to get the data property from the RowNodes into an array.
The above line can basically be assumed as:
let selectedData = [];
for (let i = 0; i <= selectedNodes.length - 1; i++){
selectedData[i] = selectedNodes[i].data;
}
In which we are just trying to get the data property into a new constant variable 'selectedData'. Look at the documentation in order to better understand this: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
const selectedData would be returned as:
[
{
make: "Porsche",
model: "Boxster",
price: 72000,
},
{
make: "Ford",
model: "Mondeo",
price: 32000
}
]
const selectedDataStringPresentation
const selectedDataStringPresentation = selectedData.map( node => node.make + ' ' + node.model).join(', ');
We take the selectedData array and concatenate the Make and Model as a single element for the array and adding a comma in the end. We would get "Porsche Boxter, Ford Mondeo".
let selectedData = [
{
make: "Porsche",
model: "Boxster",
price: 72000,
},
{
make: "Ford",
model: "Mondeo",
price: 32000
}
]
let selectedDataStringPresentation = [];
for (let i = 0; i <= selectedData.length - 1; i++){
selectedDataStringPresentation[i] = selectedData[i].make + ' ' + selectedData[i].model;
}
selectedDataStringPresentation = selectedDataStringPresentation.join(', ');
console.log(selectedDataStringPresentation);
alert()
And the last line,
alert('Selected nodes: ${selectedDataStringPresentation}');
You are going to send an alert in the browser that will display the selectedDataStringPresentation array.

Inserting values into multi-dimentional javascript array

I need to dynamically create a multidimensional javascript array that matches this layout:
array_answers[0][1]:"yes"
array_answers[1][2]:"no"
array_answers[2][2-subquestion]:"text input"
array_answers[3][8]:"yes"
array_answers[4][8-subquestion]:"text input"
The first "[ ]" defines what question it is on the page (out of totalInputs)
The second "[ ]" defines what question from the database this is (questions already in order to match the corresponding input)
and the information following is the input I am trying to add
I have attempted to the following with no luck.
for(var i = 0; i < totalInputs; i++) {
array_answers.push([i]);
array_answers[i].push([questions[i]]);
array_answers[i][0] = "yes, no, or other text";
}
The last line is where it falls apart. It would make sense to me that I should be able to use [0] to indicate that I want the first array to be given this value but with no avail.
I have also tried:
for(var i = 0; i < totalInputs; i++) {
array_answers.push([i]);
array_answers[i].push([questions[i]]);
array_answers[i][questions[i]] = "yes, no, or other text";
}
but this gives me lots of empty arrays for all the numbers from 0 to whatever the value of questions[i] is.
What am I missing or is there a simpler way to do this in jQuery while still conforming to the target layout?
If I understand you correctly, you are trying to store questions and prompts (maybe?) together in a multi dimensional array. let me suggest a different way that should work.
const array_answers = questions.map(q => [q, "yes, no, other text"]);
This may be what you want
I am still not 100% sure of what you need, but i thought I would write an answer with my assumptions, that I can update as the information improves.
The first "[ ]" defines what question it is on the page (out of
totalInputs)
This part looks like you are correct, and need to use an array. But an array is just a list of "things", in your case, questions. So where you have this line:
array_answers.push([i]);
I'm not sure it is doing what you are expecting. This is adding a new array item, which is in itself an array, that contains a single number. So if totalInputs is 3, then that first line will result in this structure:
array_answers= [[0],[1],[2]]
I think what you actually might intend here is to simply house an array of question details. Now by the complexity of your keys listed for the second dimension, it looks like an object would be more appropriate.
The second "[ ]" defines what question from the database this is
(questions already in order to match the corresponding input)
So lets go ahead and create a single question.
var question = {
anythingYouWant: 'here',
2: 'even numeric keys'
}
// you can access the values in these ways
console.log(question.anythingYouWant)
console.log(question[2])
console.log(question['anythingYouWant'])
Now once you have a question object, you can then add it to your array_answers array with push.
array_answers.push(question).
If you have two identical questions like the one above, your array will look like this:
array_answers = [{
anythingYouWant: 'here',
2: 'even numeric keys'
},{
anythingYouWant: 'here',
2: 'even numeric keys'
}]
In order to access the questions within the array, you can simply use their index:
// access second question
var secondQuestion = array_answers[1]
You can read these links to learn more about objects & arrays

JSON to Object - JavaScript

I am trying to take a JSON list that is formatted as such: (real list has over 2500 entries).
[
['fb.com', 'http://facebook.com/']
['ggle.com', 'http://google.com/']
]
The JSON list represents: ['request url', 'destination url']. It is for a redirect audit tool built on node.js.
The goal is to put those JSON value pairs in a javascript object with a key value array pair as such:
var importedUrls = {
requestUrl : [
'fb.com',
'ggle.com'
],
destinationUrl : [
'https://www.facebook.com/',
'http://www.google.com/'
]
}
Due to the sheer amount of redirects, I do prefer a nonblocking solution if possible.
You first need to create your object:
var importedUrls = {
requestUrl: [],
destinationUrl: []
}
Now, let's say you have your data in an array called importedData for lack of a better name. You can then iterate that array and push each value to its proper new array:
importedData.forEach(function(urls){
importedUrls.requestUrl.push(urls[0]);
importedUrls.destinationUrl.push(urls[1]);
});
This will format your object as you want it to be formatted, I hope.
I will propose it to you that you take another approach.
Why not have an array of importedUrls, each one with its correspondent keys?
You could have something like:
importedUrls = [
{
requestUrl: 'req',
destinationUrl: 'dest'
},
{
requestUrl: 'req2',
destinationUrl: 'dest2'
},
]
I'm sure you can figure out how to tweak the code I showed to fit this format if you want to. What you gain with this is a very clear separation of your urls and it makes the iterations a lot more intuitive.

Compare 2 Object Arrays, Javascript

Array 1:
[ user:{id:1,votes:9}, user:{id:2,votes:3} ]
Array 2:
[ user:{id:1,votes:10}, user:{id:2,votes:5}, user:{id:3,votes:1} ]
Using Node.js, what is the most efficient way to isolate the unique user based on id on it's own?
Using For loops and ForEach loops, I can't figure it out. Underscore is an option, but I still can't figure out a function process. Many thanks.
(I have no control over the way the data comes to me, modifying the array or the object isn't an option sadly)
Try this:
var ids = array1.map(function(u){ return u.id });
var unique = array2.filter(function(u) {
return ids.indexOf(u.id) < 0;
});

Problem with ordering headings in a sorted list

I am building a web application in which I build a sorted list out of an object like this:
{head: {subhead: [list_items], subhead: [list_items]}, head: {subhead: [list_items]}}.
My problem is that I have to ensure the headings and subheading always follow in a certain order. This is complicated by the fact that headings and subheadings that may be added later on also need to follow this order. So the only way I could think to inform the parser of the order would be to give it some data like this:
{heads: [head1, head2, head3], subheads: {head1: [subhead1_1, subhead1_2], head2: [subhead2_1, subhead2_2, subhead2_3]}},
but that strikes me as overly verbose and repeating data that would be in the original data structure.
You might as well use an array (or your own structure) for this since you want it to be ordered. Your own structure might look like:
function Head(name) {
this.name = name;
this.arr = [];
}
So instead of the structure:
var thing = {
food: {fruit: [apples, oranges], vegetables: [carrots, peas]},
animals: {domestic: [cat, dog], wild: [lion, bear]}
}
You might do:
var thing = [new Head('food'), new Head('animals')]
Then:
thing[0].arr.push('apples');
thing[0].arr.push('oranges');
etc.
Of course you don't have to make a class, since you can actually attach properties to arrays in javascript. But making the datastructure would be a bit more of a pain.

Categories