Removing duplicate random numbers from array - javascript

Okay so I'm looping through all the elements on the page (3) that have the class 'possible'. Then I'm creating a variable called 'other' that randomly gets a value from the array otherAnswers. Then I'm taking those values and putting them into the respected elements as text. Only thing is, most of the time the loop selects the same variable from the otherAnswers array (sometimes once, sometimes twice, others three, and rarely none of the time). How do I make sure that once the .each loops through one of the values in the array, it doesn't get it again?
$('.possible').each(function(i, obj) {
var other = otherAnswers[Math.floor(Math.random()*otherAnswers.length)];
$(this).text(other);
//otherAnswers.splice(this);
});
I've tried the commented piece of code but that just removes the values so they don't show up on my page. I have a feeling that it has something to do with the variable 'i' in the function but i'm not sure.

You can do this by taking the following steps:
Before looping, take a copy of the otherAnswers array, to avoid that you destroy it with what follows. For instance, with spread syntax:
var remainingAnswers = [...otherAnswers];
Then -- still before the loop -- shuffle the copied array randomly. Take the shuffle code from here.
shuffle(remainingAnswers);
Finally, inside your loop, access the values from that shuffled array, using the index i you already have:
var other = remainingAnswers[i];

Related

removing element from parent node with loop

today i've got this struggle to solve, so i have a array of html elements (e.g 3 inputs)
and i want to delete every single one from the dom. so i must iterate loop over them but i also should not increment the value because it will skip every other elements and that means i must only delete first element of array until it exists, so for this task i use this code
while(inputs[0]) {
inputs[0].parentNode.removeChild(inputs[0]);
}
and this works perfectly and removes all elements.
but what about for...of loop? it also gets every value of array and what if i just delete first input every time it's getting a element from array ? like this:
for(input of inputs){
inputs[0].parentNode.removeChild(inputs[0]);
}
i also tried this and in the 3 inputs it left third one (did not delete it)
so i want to know why? can someone show me how it missed third one? (graphical explanation will be the best)
Thank You
At the first iteration, the iterator is at position zero, there are three elements. You delete one.
v
0 1 2
At the second iteration, the iterator is at position one, there are two elements. You delete one.
v
0 1
At the third iteration, the iteration stops, as there is only one element, and the index is at three, so it is outside of the array. No delete operation is done.
v
0
The main problem/advantage here is that nodes is a live collection. If it would not be live (e.g. if you use querySelectorAll), then the second version would work:
// v declare variables!
for(const input of document.querySelectorAll("input"))
input.remove(); // < remove is way easier

JS is changing 2d-array values, might it be another function interfering?

Short summary: I have written some code that fills up a 2-dimensional array. When I display this array, everything is perfect. Now I give this 2d-array as a parameter to a function. When I call the function inside of
document.getElementById('output').innerHTML = myFunction(int, array);
it shows exactly the right values. However, I don't want to display them, I want to further use them. As the function returns an array (one dimensional), I tried
var my_result_array = myFunction(int, array);
I have also tried push() and pre-defined arrays or accessing just single elements.
The thing is, as soon as I have the function called in my document, the array I am giving to the function as a parameter is changing! I took care that there are no similiar names, but I just can`t figure out, why it is always changing my parameter array, therefore destroying the calculation but working fine if I use it in the document.getElementbyId part.
Any suggestions?
Edit for more code:
I try to keep it short and explainatory. I am creating an empty array with a dimension given by mat_dimension_js
var berechnungs_array = new Array(mat_dimension_js);
for (var i = 0; i < mat_dimension_js; i++){
berechnungs_array[i] = new Array(mat_dimension_js);
}
I then fill this array up with values. If I print the array, everything is fine, the values are where they belong. I then feed this array to myFunction()
Sorry for the mess, I have also tried it without creating an array A again.
I then try to grab the output of myFunction() as told above, but as soon as I do that, somehow the array I have given as a parameter changes.
Arrays in JavaScript are passed by reference, meaning that any changes you do to the array passed inside the function will also be saved in the actual array.
In addition, A = mat_array; does not create a copy of mat_array, but another pointer to it (meaning that both variables refer to the exact same array object internally).
To properly make a copy of a 1D array, calling .slice(0) should do the trick. However, for 2D arrays, you need to do this recursively.
See Javascript passing arrays to functions by value, leaving original array unaltered
What is the most efficient way to deep clone an object in JavaScript?

Changing one cell in multidimensional array updates entire column

When creating a new multidimensional array in Chrome's console like this:
var array = Array(10).fill(Array(10).fill(false));
the array looks as expected (inspect with console.table):
But when trying to change only one cell in the array: array[5][5] = true; something strange happens:
I have been banging my head against the wall for sometime because of this, but can't figure it out. Could this be a bug since Array.fill is an experimental/new feature?
It's because you actually only created two arrays. You created an inner array with 10 elements and then an outer array that has 10 elements, each of which reference the same inner array. When you change an element of the inner array and then look at the outer array, you'll see the same change in the inner array repeated 10 times.
Create your outer array with a loop instead so that a new inner array is created for every element of your outer loop.

JavaScript items disappearing from Array

I have an array called objs that holds all of my application objects. Objects get added and removed from this list depending upon what happens in the application.
I am having this problem where some objects disappear (or are overwritten) only sometimes. If I step through the add and remove functions, the app always runs as it should, however many times when it is run without the debugger, one or two objects that were added to the end of the list disappear from the list.
objects are added to the array like this:
this.objs[this.objs.length]=obj;
and are removed from the array like this:
for(var i=0;i<this.objs.length;i++)
if(this.objs[i]==obj)
return this.objs.splice(i,1);
I put this code at the end of my add and remove functions:
console.log("add! ");
console.log(this.objs);
Linked is an image of a console log during a session where an object dissapeared: http://ilujin.com/error.png
The first 4 objects in the list shown at the top should remain in the list throughout the session, but the object at index 3 (highlighted in red), gets overwritten by the next object that gets added (highlighted in blue).
The other weird thing is that the second list shown already has all of the changes (4 objects removed and 1 added), even though the remove function has only been called once and the add function not at all.
This makes me conclude that the problem is timing - if one add hasn't finished before the next add is called, the first one will be overwritten. And all of the console prints are the same because they all happen before the console can read and print.
Does this makes sense? For some reason I thought JS never ran parallel code and only moved on to a new function when the last function finished. Is the problem that I'm using the length of the objs list as the new index when I add to the list?
How can I fix this issue? I can't figure it out, and the debugger and console have proven useless.
Here is the app: http://iioengine.com/neuro/study2.htm
you only need to enter an id and see if the instructions pop up. If they do, than its working and refresh. If they don't, that means that the Text Object got overwritten.
You would really be better served by using Javascript's array methods.
Add to array:
this.objs.push(obj);
Remove from array:
this.objs.splice(this.objs.indexOf(obj), 1);
Also, note that splice edits the original array and returns the elements that have been removed. It's hard to tell from your limited code sample, but that might also be causing issues.

handling splice with associative arrays in javascript

I have an array called as wcs declared using var wcs= new Array();.
I do add items like this, wcs[indx] = value. where i will keep on changing the indx value, so at times, my array will be looking like this
wcs[2] ='a'; wcs[5]=')';
when i call the splice method on this array, all the created indices are re-indexed, meaning they become reset from 0...
how to avoid this in javascript & jQuery
Write your own splice method that works the way you want. If you specify the input, processing and expected output, you might get some help with that.
If you simply want a copy of the array, you may be after the concat method.

Categories

Resources