handling splice with associative arrays in javascript - 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.

Related

Removing duplicate random numbers from array

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

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?

why is array.splice changing the order of my array?

I have a jQuery object array that I need to remove the 1st and last item from. I tried using shift() and pop() but it threw an error because I guess a jQuery object is not the same as an array? I then used delete however that doesn't change the length so a loop I have after this gets all kinds of messed up. Finally I found out I should use:
$item.splice(0,1) and $item.splice($item.length-1, 1)
however the object array that splice(0, 1) returns is no longer in the same order as it was previously. Is there a reason splice would return a different order?
Did you try using slice? It works with a jQuery elements collection:
$('div').slice(1, -1);
Also, you can use the above statement without changing your original array. It returns the collection, removing the first and last elements.

how does javascript move to a specific index in an array?

This is more a general question about the inner workings of the language. I was wondering how javascript gets the value of an index. For example when you write array[index] does it loop through the array till it finds it? or by some other means? the reason I ask is because I have written some code where I am looping through arrays to match values and find points on a grid, I am wondering if performance would be increased by creating and array like array[gridX][gridY] or if it will make a difference. what I am doing now is going through a flat array of objects with gridpoints as properties like this:
var array = [{x:1,y:3}];
then looping through and using those coordinates within the object properties to identify and use the values contained in the object.
my thought is that by implementing a multidimensional grid it would access them more directly as can specify a gridpoint by saying array[1][3] instead of looping through and doing:
for ( var a = 0; a < array.length; a += 1 ){
if( array[a].x === 1 && array[a].y === 3 ){
return array[a];
}
}
or something of the like.
any insight would be appreciated, thanks!
For example when you write array[index] does it loop through the array till it finds it? or by some other means?
This is implementation defined. Javascript can have both numeric and string keys and the very first Javascript implementations did do this slow looping to access things.
However, nowadays most browsers are more efficient and store arrays in two parts, a packed array for numeric indexes and a hash table for the rest. This means that accessing a numeric index (for dense arrays without holes) is O(1) and accessing string keys and sparse arrays is done via hash tables.
I am wondering if performance would be increased by creating and array like array[gridX][gridY] or if it will make a difference. what I am doing now is going through a flat array of objects with gridpoints as properties like this array[{x:1,y:3}]
Go with the 2 dimension array. Its a much simpler solution and is most likely going to be efficient enough for you.
Another reason to do this is that when you use an object as an array index what actually happens is that the object is converted to a string and then that string is used as a hash table key. So array[{x:1,y:3}] is actually array["[object Object]"]. If you really wanted, you could override the toString method so not all grid points serialize to the same value, but I don't think its worth the trouble.
Whether it's an array or an object, the underlying structure in any modern javascript engine is a hashtable. Need to prove it? Allocate an array of 1000000000 elements and notice the speed and lack of memory growth. Javascript arrays are a special case of Object that provides a length method and restricts the keys to integers, but it's sparse.
So, you are really chaining hashtables together. When you nest tables, as in a[x][y], you creating multiple hashtables, and it will require multiple visits to resolve an object.
But which is faster? Here is a jsperf testing the speed of allocation and access, respectively:
http://jsperf.com/hash-tables-2d-versus-1d
http://jsperf.com/hash-tables-2d-versus-1d/2
On my machines, the nested approach is faster.
Intuition is no match for the profiler.
Update: It was pointed out that in some limited instances, arrays really are arrays underneath. But since arrays are specialized objects, you'll find that in these same instances, objects are implemented as arrays as well (i.e., {0:'hello', 1:'world'} is internally implemented as an array. But this shouldn't frighten you from using arrays with trillions of elements, because that special case will be discarded once it no longer makes sense.
To answer your initial question, in JavaScript, arrays are nothing more than a specialized type of object. If you set up an new Array like this:
var someArray = new Array(1, 2, 3);
You end up with an Array object with a structure that looks more-or-less, like this (Note: this is strictly in regards to the data that it is storing . . . there is a LOT more to an Array object):
someArray = {
0: 1,
1: 2,
2: 3
}
What the Array object does add to the equation, though, is built in operations that allow you to interact with it in the [1, 2, 3] concept that you are used to. push() for example, will use the array's length property to figure out where the next value should be added, creates the value in that position, and increments the length property.
However (getting back to the original question), there is nothing in the array structure that is any different when it comes to accessing the values that it stores than any other property. There is no inherent looping or anything like that . . . accessing someArray[0] is essentially the same as accessing someArray.length.
In fact, the only reason that you have to access standard array values using the someArray[N] format is that, the stored array values are number-indexed, and you cannot directly access object properties that begin with a number using the "dot" technique (i.e., someArray.0 is invalid, someArray[0] is not).
Now, admittedly, that is a pretty simplistic view of the Array object in JavaScript, but, for the purposes of your question, it should be enough. If you want to know more about the inner workings, there is TONS of information to be found here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
single dimension hash table with direct access:
var array = {
x1y3: 999,
x10y100: 0
};
function getValue(x, y) {
return array['x' + x + 'y' + y];
}

jquery get one object in an array as an array

With jQuery I can do
$('#some_id').find('div').first()
or
$('#some_id').find('div').last()
and get an answer like
[<div>​something</div>​]
If I do
$('#some_id').find('div')[3]
I get answer like
<div>​something</div>
How do I specify an index in array and get an array just with that object?
I would love to do something like
$('#some_id').find('div').somefunc(3)
and get
[<div>​something</div>]
I know there is slice(), but I feel like there is some simpler function that I have over looked in my hours of searching.
I know there is :nth-child() but again, it feels like there is some other function that I can call the way I call first() or last().
I am trying to chain some functions together to have one line that does what I need.
If there is not other ways, then I guess that is fine. I just wanted to make sure.
Thanks!
You can use .eq():
$('#some_id').find('div').eq(3) // This will return the fourth div inside #some_id
Since .eq() is 0-based index, if you want to get the third div you need to use:
$('#some_id').find('div').eq(2)
You can also use .get(index)
$($('#some_id').find('div').get(3)); // jQuery obj
or
[$('#some_id').find('div').get(3)]; // Array
The .get() method grants access to the DOM nodes underlying each
jQuery object. If the value of index is out of bounds — less than the
negative number of elements or equal to or greater than the number of
elements — it returns undefined.

Categories

Resources