I have made a random quiz through javascript and HTML, the questions are in a JSON file, but when I run the quiz it repeats some of the questions multiple times, how do I make it that no questions are repeated.
function renderQuestion(){
let index = Math.floor(Math.random() * availableQuestions.length);
runningQuestion = availableQuestions[index];
availableQuestions.pop(index);
let q = questions[runningQuestion];
question.innerHTML = "<p>"+ q.question +"</p>";
qImg.innerHTML = "<img src="+ q.imgSrc +">";
choiceA.innerHTML = q.choiceA;
choiceB.innerHTML = q.choiceB;
choiceC.innerHTML = q.choiceC;
}
You are trying to remove an object from an array by using
pop(index).
This is not possible since pop will always remove the last element in the array (and does not accepts any parameters!).
Use Array.prototype.splice instead:
availableQuestions.splice(index, 1); // Remove 1 element at specific index
you could push the "index" into an array, like
const usedQuestions = [];
And then when u create a new index look through the "usedQuestions" index to not use them again.
Array.pop does not accept a parameter, passing the index is not doing anything here. It is simply popping the last element from the array.
Let's say you have question array qa = [a, b, c, d, e].
You generate a random index (index = 2) and set running question to that index (runningQuestion = qa[2], => runningQuestion = 'c'). You then pop an element and the array becomes qa = [a, b, c, d].
On the next function call, it is still possible to retrieve the question c.
I recommend the following approaches
Randomize the array, and iterate over them
Instead of pop, use splice
Related
I'm in the making of a google sheets app script where I want to check if a value from one cell is in an array of values, then find what the index is so I can direct my function to that cell.
I'm at the point where I have my array in a variable called distArray, and I want to check if "id" is in that array.
Here's the code to better visualize:
function logs() {
let app = SpreadsheetApp
let dest = app.getActiveSpreadsheet().getSheetByName("Baza Danych");
let lastrow = dest.getLastRow();
let destArr = dest.getRange(2, 1, lastrow).getValues();
let id = app.getActiveSpreadsheet().getSheetByName("Zgloszenia").getRange(6, 2).getValue();
let position = destArr.indexOf(id);
Logger.log(id)
Logger.log(destArr)
Logger.log(position)
}
And here is the output I get.
My problem is that no matter what the value of "id" is, the index is either -1 or 0 meaning the value either is not in the array or is in the first cell.
Try to add .flat() at the end of the line:
let destArr = dest.getRange(2, 1, lastrow).getValues();
This way:
let destArr = dest.getRange(2, 1, lastrow).getValues().flat();
Explanation:
The method getValues() gives you a 2d array [[1],[2],[3],...].
The flat() method converts a 2d array into an ordinary flat array [1,2,3,...].
After that you will able to use array.indexOf(element) to get an index of the element in the array.
Description
Yuri's solution is a good example if you don't want to know which element of the array contains the value your looking for. But if you need to know which row of the array contains the value the following example shows how to search a 2D array.
Script
function find() {
try {
let a = [['a','b'],['c','d'],['e','f'],['g','h']];
let b = "f";
let c = a.findIndex( d => d.indexOf(b) >= 0 );
console.log("c = "+c);
}
catch(err) {
console.log(err);
}
}
7:51:23 AM Notice Execution started
7:51:24 AM Info c = 2
7:51:23 AM Notice Execution completed
Reference
Array.findIndex()
Array.indexOf()
I wanted to know how can we get every alternate object in a array. For EG -
arr = ["foo","bar","foo1","bar1"]
I Need The values -
fir_alt = ["foo","foo1"]
sec_alt = ["bar","bar1"]
If This Helps This Is My Intention -
I am trying to link localstorage and firestore using the js-sdk.. Data is in array and have to take the array to store it back in localstorage.fir_alt would be the keys and sec_alt would be values. So I Can Make it Much More Multi-Device..
Thanks In Advance
You can use the filter function to filter out even and odd index's.
arr = ["foo","bar","foo1","bar1"]
fir_alt = arr.filter((element, index) => index % 2 == 0);
sec_alt = arr.filter((element, index) => index % 2 == 1);
console.log('fir_alt', fir_alt)
console.log('sec_alt', sec_alt)
I'd use an index variable and a loop(for/next or your fav). Examine the index on each iteration of the loop, and determine if the index is odd or even(or 0), then take the appropriate action to capture the desired values.
If I know what you mean... We can be reasoned with odd and even index.
In this way:
let arr = ["foo","bar","foo1", "bar1"],
fir_alt = [],
sec_alt = [];
for (let i=0;i<arr.length;i++){
if ((i+2)%2==0) {
sec_alt.push(arr[i]);
}
else {
fir_alt.push(arr[i]);
}
}
I have an array of arrays in JavaScript that I'm storing some values in, and I'm attempting to find a way to clear the value within that array when the user removes the specified control from the page, however I'm not finding a good way to do this and anything I try doesn't seem to be working.
What is the best method for clearing the value in the array? I'd prefer the value to be null so that it's skipped when I iterate over the array later on.
I've tried to do MyArray[id][subid] = '' but that still is technically a value. I've also tried to do MyArray[id][subid].length = 0 but that doesn't seem to do anything either. Trying to grab the index and splice it from the array returns a -1 and therefore doesn't work either.
var MyArray;
window.onload = function(){
MyArray = new Array();
}
function EditValuesAdd(){
var Input = document.getElementById('Values-Input').value;
var ID = document.getElementById('FID').value;
var ValueID = ControlID(); // generate GUID
if (!MyArray[ID]) MyArray[ID] = new Array();
MyArray[ID][ValueID] = Input;
document.getElementById('Values').innerHTML += '<a href="#" id="FV-' + ValueID + '" onclick="EditValuesRemove(this.id)"/><br id="V-' + ValueID + '"/>';
}
function EditValuesRemove(id)
{
var ID = document.getElementById('FID').value;
document.getElementById(id).remove();
document.getElementById(id.replace('FV-', 'V-')).remove();
MyArray[ID][id.replace('FV-', '')] = '';
}
I've also tried to do an index of and then splice it from the underlying array but the index always returns -1.
var Index = MyArray[ID].indexOf(id.replace('FV-', ''));
MyArray[ID].splice(Index, 1);
Setting the length to zero has no effect either.
MyArray[ID][id.replace('FV-', '')].length = 0;
I would expect that one of the methods above would clear out the value and make it null so that it is skipped later on but all of the methods I've found and tried so far leave some non-null value.
What you need is an object (a Map), not an array (a list).
Here's a basic idea of how to do it :
MyArray = {};
....
if (!MyArray[ID]) MyArray[ID] = {}
MyArray[ID][ValueID] = Input;
...
delete MyArray[ID][id.replace('FV-', '')];
Check here for more information : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object
In the end I used an array of objects MyArray = [] and then using splice/findindex to remove it from the array:
function RemoveItem(id)
{
var Index = MyArray.findIndex(a => a.ID == id.replace('FV-', ''));
MyArray.splice(Index, 1);
document.getElementById(id).remove();
document.getElementById('FVB-' + id.replace('FV-', '')).remove();
}
It doesn't solve the actual question asked but I don't know if there really is an answer since I was using arrays in the wrong manner. Hopefully this at least points someone else in the right direction when dealing with arrays and objects.
I have the following task - there is an array of some items. I use random, get item number, write item's value in div and delete element with item number from array.
e.g.
array = (1,2,3)
random = 2
div = 3
delete from array = (1,2)
looping, etc
So I wrote the following script:
window.onload = function () {
var verb_array = new Array (1,2,3)
var random_verb_array = Math.floor(Math.random() * (verb_array.length - 0+0)) + 0;
var random_verb_array_2 = verb_array[random_verb_array];
var show = document.getElementById("wuza").innerHTML = random_verb_array_2;
delete verb_array[random_verb_array];
var test = document.getElementById("huza").innerHTML = '<Br><Br>' + verb_array
}
<!DOCTYPE html>
<div id="wuza"></div>
<div id="huza"></div>
Item has no value in array, but it's position still remains. How can I avoid it and finally total wipe it from the array?
You're probably looking to use splice.
verb_array.splice(random_verb_array, 1);
So assuming random_verb_array is the random index you've come up with, it'll remove 1 (second parameter) from the given index (first parameter).
Learn more about Array.splice()
var klas4 = [];
klas4[2] = [];
klas4[2]["hour"] = 1;
klas4[2]["teacher"] = "JAG";
klas4[2]["group"] = "V4A";
klas4[2]["subject"] = "IN";
klas4[2]["classroom"] = "B111";
klas4[0] = [];
klas4[0]["hour"] = 6;
klas4[0]["teacher"] = "JAG";
klas4[0]["group"] = "V4B";
klas4[0]["subject"] = "IN";
klas4[0]["classroom"] = "B111";
klas4[1] = [];
klas4[1]["hour"] = 4;
klas4[1]["teacher"] = "NAG";
klas4[1]["group"] = "V4A";
klas4[1]["subject"] = "NA";
klas4[1]["classroom"] = "B309";
This multidimensional array needs to be sorted by hour, ascending. The problem is, I don't know how to sort an multidimensional array. The first dimension (0, 1 and 2), needs to be changed, according to the hour, but all other details from dimension 2 (teacher, group etc.) also need to change from index, because otherwise the data is mixed.
You don't know how many indexes there are. In this example, the correct sequence should be: klas4[2][...], klas4[1][...], klas[0][...]
In PHP there's a certain function multisort, but I couldn't find this in jQuery or JavaScript.
klas4.sort( function(a,b){ return a.hour - b.hour } );
should do it.
It helps to think of klas4 not as a multi-array but as 1 array of objects.
Then you sort the objects in that array with a sort function.
The sort function takes 2 objects and you must return which one comes first.
You should read on sort() for Array, google that.
Also, as others have commented; the entries for klas4 are really objects, you should use
klas4[2] = {};
or even better
klas4[2] = { hour:1 , teacher:"JAG" , group:"V4A" , subject: "IN" };
Finally, I assume you are a native Dutch or German speaker, as I am. I would strongly suggest to name all your variables in English, class4, not klas4. It is the right, professional thing to do.