Assigning Array Value Gives Undefined Key - javascript

I have a multidimensional array of 100 trucks. Each truck holds several boxes.
I insert the first box of each truck by splicing from the box array to the truck array:
removed = allBoxes.splice(x, 1)[0];
trucks[i] = {0: removed};
Because I know it's the first box, I can put the {0:. But to add the next box, I want it to be dynamic.
I can insert it at the right place, but the key is undefined instead of 1 for the next box.
removed = allBoxes.splice(x, 1)[0];
trucks[i][trucks[i].length] = removed;
You can see the results here: Instead of undefined:, can it say 1? Whenever I try to add a variable in the array, it just writes out the variable string, not the value.

As #JordanBurnett mentioned, it wasn't an array. I had to count how many objects were in the array. Using the below code (from this question) gave the desired result:
var size = Object.keys(trucks[i]).length;
trucks[i][size] = removed;

Related

Why won't append row work with array?

I am trying to insert a row to the bottom of a sheet, but instead of my values I see text similar to what happens when you try to print an array in Java. I checked to see if the array is made correctly with logger and it has the values I want.
var name = e.range.getRow() + SpreadsheetApp.getActiveSpreadsheet().getName();
var array = e.range.getValues().concat(name);
Logger.log(array.toString());
masterSheet.appendRow(array);
array contains a timestamp, string1, string2, and finally the name I concatenated. Instead I get something like [Ljava.lang.Object;#7dch7145
This is because appendRow() is looking for array[] not array[][].
If you attempt to append:
var array = [[1,2,3],"some string"]
It will show up as the following as it is trying to get the entire contents of the first position of the array in a single cell. It does this by returning a string of the array object which turns out to be the native code identifier.
[Ljava.lang.Object;#32dba1e2 | some string
You can append the contents of array by appending its individual members such as
ss.appendRow(array[0])
Would append
1 | 2 | 3
It looks like a problem with your use of getValues() which returns a two-dimensional array and needs to be accessed as such.
GAS API Reference: getValues()
Return
Object[][] — a two-dimensional array of values
I believe this edit to setting your var array should do the trick, assuming your data range is for a single row (index 0 will be the first row, otherwise just change the index to the row you want):
var array = e.range.getValues()[0].concat(name);

How are items being added to this javascript array here?

Looking at a beginner's javascript book and trying to understand a small browser program that builds a list with user input. The input box displays and enters strings as input until he just adds " " as an input. Then the list is shown in the browser.
Here's the code:
var userInput = " ";
var namesArray = new Array();
while ( (userInput = prompt("Enter name", " ")) != " ") {
namesArray[namesArray.length] = userInput;
}
namesArray.sort();
var namesList = namesArray.join("<br />");
var listHolder = document.createElement('div');
var list = listHolder.innerHTML = namesList;
document.body.appendChild(listHolder);
I just don't have understanding of the way the author adds items to the array. Would someone care to explain how namesArray[namesArray.length] = userInput builds an array?
Also here's a fiddle to try it out
Thansk in advance!
So what happens is that, we get a while loop that is going to keep asking for a name until we get an empty response:
while ( (userInput = prompt("Enter name", " ")) != " ")
It then uses the length of the inital namesArray to index the new value.
namesArray[namesArray.length] = userInput;
So we know that the array is initially empty. So on the first run the length is going to be zero! We also know that an index of 0 is the first item in an array. So it adds it to the array as the first item. After that, the array now has a length of 1 (since we just added an item). So on the next iteration we add the new item to the array at the index of 1, which increases its length to 2. This goes on forver until we break the while loop.
So if we break it down we'll see it more clearly:
//First iteration
newArray.length = 0;
newArray[newArray.length] = newArray[0]
//Second iteration
newArray.length = 1;
newArray[newArray.length] = newArray[0]
etc.
Basically .length is the size of the array so .length is the next index of the array without anything in it yet. He just adds the string to the end of the array .length which creates a new position at the end of the array. .length - 1 is the last element of the array so .length would create a new position at the end of the array. The next time through the loop the length will be one greater than the previous time because you added an element to the array.
The condition for the while loop (userInput = prompt("Enter name", " ")) != " ") will remain true as long as a name is entered each time.
Each time a name is entered, the length index is assigned the name. Each time a name is assigned, the length increases. As a result, the array will grow for each name entered.
Normally you could easily add an element to an array via the .push() method. For example:
var ary = []; // empty array
ary.push('foo'); // the ary array now has one element, 'foo'
Now array indices are zero-based, meaning that you refer to the first element as [0], the second as [1], etc. However, the .length property will return the actual number of elements in an array. So if we add 10 elements to our array, asking for the length will give us 10.
So what the person who wrote that code is doing, is using the fact that the .length property will allow you to target an element of the array that doesn't exist yet -- the element after the last element.
So for example, say we have an array with 10 elements. The length property will be 10, however the index of the last item will be nine, since the indices are zero-based. When the author of that code does:
namesArray[namesArray.length] = userInput;
They're also saying namesArray[10] = userInput;, and assigning userInput to the eleventh spot in the array (remember, zero-index).
Since this can be a little confusing to follow, most programmers will simply use the .push() method, which automatically tacks the value you pass it onto the end of the array without you having to specify an index.
Since arrays are indexed starting from zero, the last element in the array always has the index
namesArray.length - 1
Therefore, the next available unused index is always equal to
namesArray.length
You can safely set values at this index and know that they will be added to the end of the array.
So, you have this array:
var namesArray = new Array();
And you may know you can insert array values like this:
namesAray[0] = 'first value';
namesAray[1] = 'second value';
namesAray[2] = 'third value';
Now, the code is like this:
namesArray[namesArray.length] = userInput;
So, here the namesArray.length brings you the size of the array. Ok, as above you see I've added three values to the namesArray namesArray[0],namesArray[1], namesArray[2]. So the current size of the array is 3 and namesArray[namesArray.length] is equal to namesArray[3] and now here the input value is inserted.
So, like this the code inserts new array value to the end index of array which is checked by while ( (userInput = prompt("Enter name", " ")) != " ") {
Hope you understood.

javascript array show undefined when escape one index

I face a problem when tried to assign a value with a specific index. suppose I have javascript variable like
var track = new Array();
Now I assign a value for a specific index like-
track[10]= "test text";
now array has one value and it's length would be 1. But the main problem is it show it's length is 11.
alert(track.length); // 11 but I expect 1
and if I print its value then it shows like--
alert(track); // ,,,,,,,,,test text
and if I console this array then it show like below--
console.log(track); // undefined,undefined,undefined,undefined,.....,test text
I am very much confused because I assign only one value but it show 11. How it assign it's value and what characteristics array variable shows. Can anyone explain me and how to get its length 1 using below code--
var track = new Array();
track[10]= "test text";
alert(track); // test text
alert(track.length); // 1
console.log(track); // test text
The Array object automatically fills in the missing indexes. The reason it gives length 11 is because the index starts at 0.
If you are wanting to use key-value just use an object.
var track = {};
It will not have a .length value however.
javascript automatically fills in the array to push the element you want. You can get the "true" count by doing this:
track.filter(Boolean).length
However note that this will only "work" if you do not have any other elements that resolve to "false" value (eg. empty strings or setting them to false) so if you want to this, make sure you never actually set any other array elements to a falsy value so that you can use this convention. For example if you want to set other array values to a falsy value, use something like -1 instead as the thing to check.
Since you're setting the value for 10th position it's showing array size of 11
You must start from 0th position..
var track = new Array();
track[0]= "test text";
alert(track); // test text
alert(track.length); // 1
console.log(track); // test text
Try this
For such kind of operations i generally prefer the library called Underscore.js.
It abstracts array manipulations. You might want to checkout the compact method
Compact works like this:
_.compact([undefined, undefined, undefined, "test test"]) as ["test test"]
Then you can check the length of the returned array.
Though a simple approach is
filter(Boolean).length
But if you want to use the array then you might like underscore.

How does this snippet for removing duplicates from an array work

Regarding this post (Remove Duplicates from JavaScript Array) on creating a new array of unique values from another array.
Code in question:
uniqueArray = myArray.filter(function(elem, pos) {
return myArray.indexOf(elem) == pos;
})
Using this as the test data:
var names = ["Mike","Matt","Nancy","Adam","Jenny","Nancy","Carl"];
Desired result is an array with only unique values:
var unique_names = ["Mike","Matt","Nancy","Adam","Jenny","Carl"];
Where I'm at:
I understand that filter will run a function on each member of the array, and that elem is the element being reviewed, and that pos is its index. If something causes that function to return false, then that element will not be included in the new array. So walking through it, this happens:
Is myArray.indexOf("Mike") the same as 0? Yes, so add "Mike" to the new array.
Is myArray.indexOf("Matt") the same as 1? Yes, so add "Matt" to the new array.
Is myArray.indexOf("Nancy") the same as 2? Yes, so add "Nancy" to the new array.
[repeat for all elements. All pass.]
Basically I don't get why the 2nd Nancy would evaluate to false.
The indexof is the index of the first appearance of the element, so the second Nancy would get the index of the first Nancy, and would be filtered out.
6) Is myArray.indexOf("Nancy") the same as 5? No (it's 2, just like it step 3), so skip the duplicated "Nancy".
indexOf gives you the first occurrence of the item.

Select element from json dynamically

I have a an associative array in php that i parse to get json from it (json_encode) then i store the result in a javascript var
var myArray = <?php print json_encode($phpArray); ?>;
Now whene the user hit a button i should choose another element from the array dynamically, for example, i chose a random first element :
var an_element = myArray.a2.link;
-'a2' is an array in the main array
-'link' is an element in the a2 array.
So now whene the user hit my button, i want to choose a random other array id (for example a5, a9, etc.)
I tried this :
var randomnumber=Math.floor(Math.random()*101); // choose random number
var newRandomArrayID= "a"+randomnumber;
an_element = myArray.newRandomArrayID.link;
It doesn't works, it says myArray.newRandomArrayID is undefined.
Anyone can help?
Thank you
You need to use [] indexing to find properties by name:
an_element = myArray[newRandomArrayID].link;
Otherwise JS is looking for a property actually called newRandomArrayID on myArray rather than using the value of the variable to lookup the property.

Categories