Create a nested array? [closed] - javascript

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
I'm creating a trivia game which will give the user 4 answer to pick from. Is using an array to include the question and the answer a good option for this game? and if so what is the proper way to create a nested array.

So... in js it's not a problem to make a nested array, but it is a problem if you're thinking of key => value type of array, in that case you need to use an object, you can foreach it's properties as you would with array IF you'd need to. You can store answer values in array (I've been there with exactly the same thing you want to do so trivia learning game), but you can always use objects and do something like that
var userAnswer = 'something',
item = {
question: 'what is a?'
answers: [ 'a', 'b', 'c' ]
validAnswer: 0;
}
if(userAnswer === item.answers[validAnswer]) {
console.log("is valid");
}
some other usage:
var userStats = {
status: 'alive',
makeDead: function() {
this.status = 'dead';
},
bringBackToLife: function() {
this.status = 'alive';
},
}
//then you can even do things like...
userStats.makeDead();
console.log(userStats); //user will be dead
userStats.bringBackToLife(); //user status will be alive
I mean you should be fine with array for keeping just question or question and (nested[[]]) array of answers, but then you're starting to play game of array[0] (should be question right?) array[3] (should be invalid answer?) and then what? if you still think your trivia game will never grow then you might stick to that solution, but if you think it might ever evolve just use objects to keep stuff organised.
update
Try to keep your objects small & dont make 'god' objects (look up SOLID rules), though if you want to let's say save/have a lesson containing some questions then you could have one big object containing a lot of small ones, i.e.
//you can make object to store some data and functions
var LessonItem = function(question){
this.question = question;
this.answers = [];
this.addAnswer = function(answer){
this.answers.push(answer);
};
};
//you dont need the 'valid' part if there's always just one valid option
var question1 = new LessonItem('What is?');
question1.addAnswer({text: 'It is something', valid: true });
question1.addAnswer({text: 'It is something not', valid: false });
question1.addAnswer({text: 'It is something 3', valid: true });
//and this would be our 'big' object, i.e. to save in json file or whatever
var lesson = {
lesson_subject: 'something',
lesson_repeat: 3,
lesson_score: 124,
lesson_items: [
question1,
//question2
]
};
console.log(lesson);
but yeah, you can have big 'object' to 'store' others, but avoid creating god-like one huge objects managing everything cause it will become hell with time :D as well im not sure if you're doing that but you can paste in your javascript in google chrome tools console and check if it's working right without reloading page... (for quick checks :))

Related

Array Operations: Which way you will prefer, why? is there any better way? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 months ago.
Improve this question
To check if an element exist in an array, which method is better? Are there any other ways to do a boolean check?
type ObjType = {
name: string
}
let privileges: ObjType[] = [{ name: "ROLE_USER" }, { name: "ROLE_ADMIN" }, { name: "ROLE_AUTHOR" }];
//method 1
const hasAdminPriv = privileges instanceof Array && privileges.find((ele: ObjType) => ele.name === "ROLE_ADMIN");
//method 2
const found = privileges instanceof Array && privileges.find((ele: ObjType) => ele.name === "ROLE_ADMIN") !== undefined;
//method 3
const privilSet = new Set<string>();
privileges.forEach((element: ObjType)=> privilegeSet.add(element.name));
//method 4
const privilegeSet2 = new Set<string>(privileges.map((element: ObjType) => element.name));
console.log(privilegeSet2.has("ROLE_ADMIN"));
That most likely depends on the way you want to use this.
The set conversion could be benefical, if you intend to query for multiple things at a time.
Maybe you'd rather use some for your query, if you're really only interested if a value is in the array and not for the rest of the object.
I'd also suggest having a look at includes as that can be exactly what you're looking for at least for trivial objects in an array.
That being said, if forced to use one of the provided methods, I'd argue that method 2 is best if you want to check for one value and method 4 if you either want to query multiple values or can cache the generated set for big arrays and relatively often asked queries.
Side note:
If your whole code is in typescript, I don't really see why you would use
privileges instanceof Array. Of course this may be necessary if the array comes from some js code or a file, but even then I'll argue that you should check the type when you receive the array and than assume that it is an array if it is typed that way.

How do I check for property2 value in the same item after property1 value passes a condition? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
This is how my array is set up:
"members" : [
{ "health" : 0,
"stateStr" : "Not reachable",
},
{ "health" : 1,
"stateStr" : "PRIMARY",
},
{ "health" : 1,
"stateStr" : "ARBITER",
}
],
What I'm trying to achieve is to iterate through all 3 members, and find if a member has stateStr = Primary (in the above example, member[1] will pass this condition). If that condition passes, look at the same member and see if health=1. In the above example, I would then look at if member[1].health =1. I'm not sure how to store that index of member.. I would appreciate it if you could show me exactly - I'm very new!
Here's the logic of it:
If any member has stateStr=Secondary. If yes, then print
"Secondary node is still running." and break.
Else, Check if any member has stateStr="Primary". If Primary is found, check whether its health = 1
If none of the members are Primary, then print "No primary node
found" and if Primary node is found but its health !=1, then print
"Primary node unhealthy" and break.
Repeat the previous three steps for stateStr="Arbiter"
Arrays in JavaScript can be iterated through with a for-loop.
for (var i = 0; i < members.length; i++) {
if (members[i].stateStr == "PRIMARY") { // 1st condition
if (members[i].health === 1) { // 2nd condition
// store index i here
}
}
}
Understand that in the above for-loop, members[i] only gets the element containing the JSON object. We must then specify the JSON property after a period.
The way a JSON object works in this case is by indicating the JSON property name after a period for that element of the array. In simple terms, it works this:
members[i].JSON_PROPERTY
See this question and this on more about iterating through arrays with JSON. There is more than one way to do this too. This one is fairly common.
Lastly, remove the comma , at the end of the members array in the declaration. it should end with a ; since it's the end of the array declaration:
{ "health" : 1,
"stateStr" : "ARBITER",
}
];

creating a multiple choice quiz with array

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);

I need to console log my anser and not just return it [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I need to console log my anser and not just return it
I have tried this however in my console it does not LOG it but returns (3) ["JavaScript", "CSS", "HTML"]
I need it to return
* HTML,CSS,JAVASCRIPT
function logReverse(input) {
let arr = input.reverse();
console.log(arr)
}
//test
logReverse(['HTML', 'CSS', 'JavaScript'])
Please help out
When you run code in the console, return values are displayed as well as any console output. What you should see in the console when you run that code is:
Array(3) [ "JavaScript", "CSS", "HTML" ] - this is the console.log, logging the object you have passed it
undefined - this is the return value of the function
When you said you need it to return HTML,CSS,JavaScript, I assume what you actually want to do is to take a string value of the reversed array, which would look like this:
console.log(Array(...input).reverse().toString())
Note that I've wrapped the input in Array(...input), which creates a new array. Array.prototype.reverse will reverse the array in place, which means that it changes the value of reverse. By making a new array, you can avoid modifying the input.
The call to Array.prototype.toString will join the elements with commas, which I believe is the desired effect you're after.

Dynamically remove and add strings in localstorage [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm currently working on a HTML5 project and I need to use localstorage.
I want to be able to dynamically remove items from my localstorage. This means that if I have five items, and I want to remove the second item, the third, fourth and fifth item will be automatically allocated to a lower place so that I don't have a gap left (as this is very annoying when I want to print my whole local storage).
HTML5 localStorage aka Web Storage, uses keys to store string values. So you can store objects or arrays by converting them to JSON before storing:
// define an array of objects
var arr = [
{ name : 'first', description : 'first description' },
{ name : 'second', description : 'second description' },
{ name : 'third', description : 'third description' }
];
// store the array to localStorage as a JSON string
localStorage.setItem("data", JSON.stringify(arr));
// retrieve the JSON from localStorage and parse it back to an array
var arr = JSON.parse(localStorage.getItem("data"));
// remove the second object from the array
arr.splice(1, 1);
// let's update the first object too
arr[0].name = 'first name';
// save it back to localStorage
localStorage.setItem("data", JSON.stringify(arr));
if (localStorage.text)
{
var text1 = localStorage.text;
var splitText1 = text1.split(',');
if (splitText1.length > 0)
for (i in splitText1)
{
var div = document.createElement("div");
div.setAttribute("id", "medicament");
div.innerHTML = "<h1>" + splitText1[i] + "</h1>"; document.body.appendChild(div);
}
}
This is the code we use to print things on our screen.
You can use jstorage to solve your problem.

Categories