Iterating over two arrays at a time in Javascript - javascript

I want to iterate over two arrays at the same time, as the values for any given index i in array A corresponds to the value in array B.
I am currently using this code, and getting undefined when I call alert(queryPredicates[i]) or alert(queryObjects[i]).
I know my array is populated as I print out the array prior to calling this.
//queryPredicates[] and queryObjects[] are defined above as global vars - not in a particular function, and I have checked that they contain the correct information.
function getObjectCount(){
var variables = queryPredicates.length; //the number of variables is found by the length of the arrays - they should both be of the same length
var queryString="count="+variables;
for(var i=1; i<=variables;i++){
alert(queryPredicates[i]);
alert(queryObjects[i]);
}

The value of the length property of any array, is the actual number of elements (more exactly, the greatest existing index plus one).
If you try to access this index, it will be always undefined because it is outside of the bounds of the array (this happens in the last iteration of your loop, because the i<=variables condition).
In JavaScript the indexes are handled from 0 to length - 1.
Aside of that make sure that your two arrays have the same number of elements.

If queryPredicates does not have numerical indexes, like 0, 1, 2, etc.. then trying to alert the value queryPredicates[0] when the first item has an index of queryPredicates['some_index'] won't alert anything.
Try using a for loop instead:
stuff['my_index'] = "some_value";
for (var i in stuff)
{
// will alert "my_index"
alert(i);
// will alert "some_value"
alert(stuff[i]);
}

Arrays in JS are zero based. Length is the actual count. Your loop is going outside the bounds of the array.

Related

For loop in JavaScript I want some knowledge about the program that is given below [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 1 year ago.
Improve this question
function multiplyAll(arr) {
var product = 1;
for (var i = 0; i < arr.length; i++) {
for (var j = 0; j < arr[i].length; j++) {
product * arr[i][j];
}
}
return product;
}
const result = multiplyAll([[1,2],[3,4],[5,6,7]]);
console.log(result);
Q1. What is arr[i]?
Q2. I just saw the arrays made like var multiplyAll = [[1,2],[3,4],[5,6,7]] so I am not getting the point of the Array made in the above code I specified?
If any one could help me with understanding this code then the help would be much appreciated because I don't want to get into the next question without getting my basics cleared.
Your function is called with a matrix, i.e. a 2-dimensional array. In JavaScript this is represented as an array of arrays. The outer array has one entry per row, and each row itself is an array of values.
Q1. what is arr[i] ?
It is one row in the matrix: the one with index i. It is an array, which is why you can specify another index for that array, like arr[i][j] It means: take the row at index i and from that array take the value at index j.
Q2. I just saw the arrays made like var multiplyAll = [[1,2],[3,4],[5,6,7]] so I am not getting the point of the Array made in the above code.
It creates a two dimensional array on-the-fly. While you can use such a literal to initialise a variable through the assignment operator (which you seem to understand), you can also provide it as argument for a function call. The corresponding parameter variable arr will then receive that as its initialisation value. So in a way it is also an assignment, just not with the = operator.
Pretty much what this function does is it receives a 2d-array (so that is an array of arrays). This means that arr[i] is an array itself; the first array in the outer array.
The concept of 2d arrays is quite useful, for example for grids or boards. Although at first glance they seem weird they are not too bad once you understand them. It helps to not cramp them into 1 line:
var multiplyAll = [
[1,2],
[3,4],
[5,6,7]
]
Q2: The array in multiplyAll([[1,2],[3,4],[5,6,7]]); is being created as a function argument and not assigned to a variable. When you use var array = [1, 2, 3] the [1, 2, 3] part creates the array, the var array = part is just used to assign the array to a variable. When the function multiplyAll is called the array [[1,2],[3,4],[5,6,7]] is being passed in as the first argument so inside the function it is assigned to arr.
Q1: arr[i] is used to reference the 'i'th element in arr. For example if I had var arr = [3, 5, 4] and I used arr[0] it would reference the 0th (first) element in arr or 3
arr[i] is an array within the array i being the index
this function doesn't do anything because of this line product * arr[i][j]; it's not changing the array just multiplying it by 1 "in the air"- without saving it to a variable
and then the function just returns product which is always 1, that's why this function is wrong it just returns 1
a function, takes in some sort of input, and does something, or returns something (this means that the function outputs something and you can use the function as part of an expression). this function returns the variable product.
the input is arr(the name doesn't matter) and it's supposed to be an array. An array is something like a list. for example [1, 2, 3] is a list of numbers. and you can get a specific index of that array by saying arr[0], because arrays start at 0, arr[0] is the value 1.
You can have an array of strings ["hello", "world"] and everything, so there's no reason way you can't have an array of arrays for example [[1, 2], [3,4]] in this array, arr[0] is the first value, which is [1,2], which itself is an array, meaning you can access the first value there by saying arr[0][0].
ok, about the function specifically:
a variable named product is declared with the value 1. it is a number.
and there's a loop that basically says "make a variable named i and set it to zero. keep looping and add 1 to the variable i until it i is not less than the length of the array anymore." this means that the first loop loops as many times as the length of the outer array.
and each time the variable i increases. and instead of a number arr[0], you can put a variable in the brackets, so it's arr[i]. remember arr is an array of arrays, so arr[i] is another array.
this should answer question 1
inside this loop, there is another loop, which loops through the "inner" array. the logic for this is the same, just with a variable named j. these two loops mean that for every loop of the outer for loop, the inner for loop loops through all of the "inner" array.
inside the 2 for loops, you now have access to both i and j. this goes through all possible values. so if you were to console.log(i,j), it would print something like this
0 0
0 1
1 0
1 1
2 0
2 1
2 3
if you do arr[i][j] now, when all of the loops are finished, it should go through all of the values. it multiplies product by that value. (i think it's supposed to be product *= arr[i][j]). in the end, it will return all values multiplied together
I think I probably repeated many things you already knew but I think this explains everything.

Why can my js code set values to undefined array indexes?

As I know an Array element in JavaScript can itself be another Array, hence creating layers of arrays within one another. I am tring to define an array like:
[Array(821), Array(821), Array(821), Array(821)]
As You see, this is an array with 4 elements each of which will contain an array of 821 elements.
Now, I also know Arrays can be dynamically resized using Array.push("new value") method, otherwise an undefined error will be thrown. Therefore, I defined each and every one of the array elements as being an array itself:
var htmlOBJs = {};
htmlOBJs.tabular = [];
for (var i = 0; i < 5; i++){
htmlOBJs.tabular.push([]);
}
Now, when I want to access an element inside the inner array htmlOBJs.tabular[2][100], surprisingly no undefined error is thrown. Why? Am I not supposed to push indexes up the inner array up to 100?
The reason the undefined error isnt thrown is as you push to the tubular array this causes a new entry created. This means now it is a multidimensional array. To cause the undefined error to throw you would have to go 3 levels deep.
There is an interesting reason for empty arrays which has been described way better but basically the first parameter for the Array constructor is a size and not actually filling this array:
to do this you can use the fill method: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill - you may need to map over this after to make sure these are unique values.

Length of the javascript array does not change after deleting the element from it

I am trying to copy one array values into another, but without breaking the links that is associated with this array other words i can not just assign the new array to this value, thats why i cannot use methods like slice() or concat().
Here is the code of the function that does the thing:
self.updateBreadcrumbs = function (newBreadcrumbs) {
var old_length = self.breadcrumbs.length;
var new_length =newBreadcrumbs.length;
var j = new_length > old_length ? new_length: old_length;
for (var i = 0; i < j; i++) {
if(old_length < i+1){
self.breadcrumbs.push(newBreadcrumbs[i]);
continue;
}
if(new_length < i+1){
delete self.breadcrumbs[i];
continue;
}
if (self.breadcrumbs[i].title !== newBreadcrumbs[i].title) {
self.breadcrumbs[i] = newBreadcrumbs[i];
}
}
}
My problem is that length of the array does not change when i delete something from the array.
P.S If you know any easier way to do this i am totally open for propositions.
Length of an Array can never change by deleting elements in it.
However It can be altered with splice
eg.
var arr=[1,2,3,4,5]; //length 5
arr.splice(0,1); //length 4
Unlike what common belief suggests, the delete operator has nothing to do with directly freeing memory. delete is only effective on an object's properties. It has no effect on array length
The splice() method changes the content of an array by removing
existing elements and/or adding new elements.
More about Splice
The length property of an Array object is a property that is maintained by it's methods, it is not an inherent characteristic of the object itself. So, if you take an action on it that is not one of Array's own methods, it will not update the length property. In this case, it is the splice method that you would want to use ( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice )
Interestingly, you can change the makeup of an array by directly altering its length . . . for example, if you have an array with 6 elements in it and you were to change its length property to 5 (i.e., array.length = 5;), it would no longer recognize the 6th element as being part of the array.
More on the length property: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/length
An Array is (aside from its prototype methods) not much more than a simple object. The difference is in the length property which has a spcieal setter method, and the different way of adding a new property.
If a property is added to the object, its name is tested for being a numerical value and whether this value is >= the current array length. if so, the internal length is updated.
If the length is set, it is checked, whether the new value is smaller than the old one, and if so, all own properties with a property name that is a numerical value and >= the new length will be deleted.
If you delete an indexed element from an array, it will just be deleted (and accessing this index later will return undefined, as it would do with any non-existent property). It won't change the array length, nor will increasing the array length create any properties for the added index positions (sparse array). Using [] or new Aray[10000] will both create Arrays with exactly the same memory footprint. Just the length property has a different initial value.
This is completely different from Arrays in other languages, where an array of size n will have n storage spaces reserved for the elements (being pointers to objects or being native value types). So in other languages, creating an array with a given size and filling it is faster than creating an empty array and adding values (in which case each time a larger consecutive space must be allocated and the array must be copied to this larger memory psoition before adding the element). OTOH, accessing the elements of an JS array is somewhat slower (as they are just named properties which have to be located in the property list first) than in other languages where an element is at its given, fixed position.
This answer will not help if you use array, but.
If you still need to delete item by key and you can use object:
$o = {'blue' : '', 'apple' : '', 'red' : ''};
console.log(Object.keys($o).length); // will output 3
delete $o['apple'];
console.log(Object.keys($o).length); // will output 2

Remove objects from array - Two different approaches, two different results when consulting the length of each array

I have two identical arrays: itemsOutput& itemsOutput2
I want to delete those objects in the arrays with attributes.type = "DIMENSION". I have found two different methods for doing so:
Method 1
jQuery.each(itemsOutput, function(i, val) {
if(val.attributes.type == "DIMENSION") // delete index
{
delete itemsOutput[i];
}
});
console.log(itemsOutput.length);
Method 2
metrics = itemsOutput2.filter(function (el) {
return el.attributes.type === "METRIC";
});
console.log(metrics.length);
Although both new arrays seem to have the same number of objects (and in both, all objects with attributes.type = "DIMENSION" are gone), the console shows two totally different values for the length of each array.
Method 1 removes the objects, but length is the same as the original array (although exploring the array in the console I observe that the objects keep their original indexes)
Method 2 not only removes the objects, but it also reassings the indexes successively. And for me, the code seems more clear, so I will stay with this method.
My question is, however, why this happens and if there could be problems if I use the results of method 1 in a loop, for example.
When you delete an array element, the array length is not affected. This holds even if you delete the last element of the array. When the delete operator removes an array element, that element is no longer in the array but the length stays the same.
You will need to use method splice if you want to remove it from the array. For example:
itemsOutput.splice(i, 1);

Is an array in JS actually filled with empty spaces or when printed is it filled with zeros?

I have an array:
mydata =[];
i am storing values in the array by using a numeric key that can be somewhat big
mydata[13525] = 1;
However if i only store one item as the above, when i print the array in the console it prints 13524 commas before the object, nevertheless the debugger tells me it has length 13526 and there is only one element in the array.
I am confused as i understood that JS arrays do not required every position to be filled and certainly this might consume a lot of memory on bigger numbers. Can you explain please?
The .length property of an array represents the highest index plus one in the array that has been assigned a value.
When you do not assign intermediate values (and thus have a sparse array), the intervening values that you have not assigned are undefined which is essentially the "nothing here" value in Javascript. The console chooses to display arrays by trying to show you every value between 0 and the end of the array which is simply not a very good way to display a sparse array that is mostly empty. That's more an artifact of a design choice in the console than anything else. One could design a different way to display contents of an array that would handle sparse arrays differently.
Arrays are most efficient if you use consecutive indexes started from 0. That's what they are mostly designed for and what many implementations are optimized for since a runtime can do some optimized things if it knows there is a sequential set of values.
If you know you're going to mostly not be using sequences of numeric indexes starting from 0 and as such the .length property is of little use to you, then perhaps a plain object with arbitrary properties is a better choice.
var mydata = {};
mydata[13525] = 1;
console.log(mydata[13525]); // 1
console.log(mydata.length); // undefined - no .length property on an object
console.log(myData); // {1: 13525}
If you only want to print any non-null value in the array, instead of printing the whole array I'd use a for loop that only prints non-null values. It'd be something like this...
for (i = 0; i < mydata.length; i++) {
if(mydata[i]!= null){
console.log(mydata[i]);
}
}
javascript array is bit different from others,
var foo = [1, 2, 3, 4, 5, 6];
foo.length = 3;
foo; // [1, 2, 3]
foo.length = 6;
foo.push(4);
foo; // [1, 2, 3, undefined, undefined, undefined, 4]
While the getter of the length property simply returns the number of elements that are contained in the array, in setter, a smaller value truncates the array, larger value creates a sparse array. Guess what the setter mydata[13525] = 1; would do.
src: Javascript Garden
Edit:
to print/use only the values present, you can do
mydata.forEach(function(v){console.log(v);});

Categories